European Windows 2012 Hosting BLOG

BLOG about Windows 2012 Hosting and SQL 2012 Hosting - Dedicated to European Windows Hosting Customer

SQL Server Hosting - HostForLIFE :: SQL Primary Key: Syntax, Uses, and Illustration

clock May 15, 2024 08:06 by author Peter

A primary key constraint is a key that has one or more columns to help identify each tuple or record in a table individually.

Qualities
Only distinct values should be assigned to the column designated as the primary key; duplicate values are forbidden. The primary key column contains no NULL values. As a result, there is a necessary value in the column holding the primary key. There is only one primary key per table, even if a primary key may contain more than one column.

Adding a new row using an existing primary key is not feasible.

categorized as,

  • A single-column, basic primary key.
  • Multiple columns make up the composite primary key.

As stated in the Make a Table or Modify a table statement.

A PRIMARY KEY constraint can be used to create the primary key in a table.

It can be created at a couple of levels.

  • Column
  • Table

SQL Primary Key at Column level
The primary key should be defined at the column level if it only has one column. The primary key "primary_field_name" is created in the table by the following code.

Syntax

Field_name data_type PRIMARY KEY

Example

CREATE TABLE Employee
(
  Id INT NOT NULL PRIMARY KEY,
  [Name] VARCHAR(50) NOT NULL,
  City VARCHAR(20) NOT NULL
)


Let’s verify the primary key with an example.
INSERT INTO Employee
VALUES (1, 'Peter', 'Scott');

Let’s try the execution of the same query again in SQL.

It will throw an exception.

Let’s try with the NULL inserted as the primary key value.
INSERT INTO Employee
VALUES (NULL , 'Peter', 'Scott');

It will throw an error due to null not being allowed in the primary key.

SQL Primary key at Table level

Whenever the primary key contains more than one column, it has to be specified at the table level.

Syntax
CREATE TABLE table_name
(
  field1 data_type,
  field2 data_type,
  ...
  PRIMARY KEY (field1)
)


Example
CREATE TABLE Employee
(
  Id INT NOT NULL,
  [Name] VARCHAR(50) NOT NULL,
  City VARCHAR(20) NOT NULL,
  PRIMARY KEY (Id)
)


Primary Key with Multiple Columns

If you want to add a primary key to more than one column, then that is not possible at the column level; that is possible at the table level.
CREATE TABLE Employee
(
  Id INT NOT NULL,
  [Name] VARCHAR(50) NOT NULL,
  City VARCHAR(20) NOT NULL,
  PRIMARY KEY (Id, [Name])
)

Primary Key with Alter Table
The primary key is typically defined at the time the table is created, but occasionally it might not be created in the table that already exists. However, we can use the Alter Statement to add the primary key.

For a Single Column

Syntax
ALTER TABLE Table_name
ADD PRIMARY KEY (column1);

Example
ALTER TABLE Employee
ADD PRIMARY KEY (Id);


For Multiple Columns
Syntax
ALTER TABLE Table_name
ADD CONSTRAINT primary_key_name PRIMARY KEY (column1, column2);


Example
ALTER TABLE Employee
ADD CONSTRAINT Employee_PK PRIMARY KEY (Id, [Name]);

Remove Primary Key
We can remove the primary key constraint from a table using the DROP statement.

Syntax
ALTER TABLE table_name
DROP CONSTRAINT primary_key_name;

Example
ALTER TABLE Employee
DROP CONSTRAINT Employee_PK;


We learned the new technique and evolved together.
Happy coding!

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.


 



SQL Server Hosting - HostForLIFE :: Run Multiple SQL Files in a Single SQL Server Execution

clock May 6, 2024 10:05 by author Peter

Do you make use of SQL Server? Do some teams or DBAs still manage deployments by hand? Are project or financial constraints preventing the incorporation of CI/CD tools? However, there's a chance to use more than one SQL script.

Overview
Running SQL scripts is a standard procedure in database management. But handling several SQL files might make the procedure tiresome and time-consuming. Batch scripts are one of the ways that SQL Server offers for executing SQL scripts. We will examine how to effectively use a batch script to run several SQL files in SQL Server in this article.

Understanding Batch Scripting
Batch scripting is a powerful tool for automating tasks in Windows environments. It allows users to execute a series of commands or scripts in a sequential manner. These scripts are saved with a .bat extension and can be run by simply double-clicking them or through the command line.

Pre-requisite for Batch File

    This script deploys all the .sql files present in a directory or sub-directories in an order.
    NO SPACE in .sql file name.
    NO SPACE in sub-directories.
    To execute .sql in order, add a numeric sequence as follows:
    createtable.sql
    insertdata.sql
    execstoredproc....etc.
    Specify the SERVERNAME, which is mandatory.
    DATABASENAME is optional (Commented-out). In case enabling add (-d%dbname%) after -E at line like (SQLCMD -S%SERVERNAME% -E -d%dbname% -b -i%%G >> :: :: %logfilepath%).
    Specify the SCRIPTLOCATION, which is mandatory.
    The execution log will be captured on the same SCRIPTLOCATION for successful execution and failure.

Steps to Follow

  • Copy the below batch script and save it as "ExecuteSQLFiles.bat".
  • Update SERVERNAME, SCRIPTLOCATION, and LOGLOCATION accordingly for your needs.


    :: Pre-requisites to follow

    :: This script deploys all the .sql files present in a directory or sub-directories in an order.
    :: NO SPACE in .sql file name.
    :: NO SPACE in sub-directories.
    :: To execute .sql in order add numeric sequence as follows: 1.createtable.sql,
    :: 2.insertdata.sql, 3.execstoredproc....etc.
    :: Specify the SERVERNAME which is mandatory
    :: DATABASENAME is optional (Commented-out). In case enabling add (-d%dbname%) after -E at line like
    :: (SQLCMD -S%SERVERNAME% -E -d%dbname% -b -i%%G >> :: :: %logfilepath%).
    :: Specify the SCRIPTLOCATION which is mandatory.
    :: The execution log will be captured on the same SCRIPTLOCATION for successful execution and failure.

    @echo off
    setlocal enabledelayedexpansion

    set SERVERNAME=LAPTOP-AOVLBDQ4
    ::set DATABASENAME=MyWork
    set SCRIPTLOCATION=C:\Peter\AutoDepSQLFiles\SQL\
    set LOGLOCATION=C:\Peter\AutoDepSQLFiles\Logs\
    set hr=%time:~0,2%

    if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
    set logfilepath= %LOGLOCATION%\ExecutionLog_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.log
    set cmd='dir %SCRIPTLOCATION%\*.sql /b/s'

    FOR /f %%G IN (%cmd%) DO (
    echo ******PROCESSING %%G FILE******
    echo ******PROCESSING %%G FILE****** >> %logfilepath%
    SQLCMD -S%SERVERNAME% -E -b -i%%G >> %logfilepath%
    IF !ERRORLEVEL! NEQ 0 GOTO :OnError
    )
    GOTO :Success

    :OnError
    echo ERROR ERROR ERROR
    echo One\more script(s) failed to execute, terminating bath.
    echo Check output.log file for more details
    EXIT /b

    :Success
    echo ALL the scripts deployed successfully!!
    EXIT /b


Copy the below SQL scripts into separate files in respective folders.
--File Name 1.TableCreation.sql

USE MyWork
GO

CREATE TABLE dbo.Employee (Id INT IDENTITY(1,1), Emp_Name VARCHAR(100))

--File Name 2.InsertData.sql

USE MyWork
GO

INSERT dbo.Employee
SELECT 'Peter'
UNION
SELECT 'Scott'


--File Name 3.AlterTable.sql

USE MyWork
GO

ALTER TABLE dbo.Employee ADD Email VARCHAR(200)

--File Name 4.UpdateTable.sql

USE MyWork
GO

UPDATE dbo.Employee
SET Email = '[email protected]'
WHERE Emp_Name = 'Peter'

UPDATE dbo.Employee
SET Email = '[email protected]'
WHERE Emp_Name = 'Scott'


  • Execute the bat file, and upon successful completion, a log file will be generated in the Log directory.
  • All SQL scripts within the folder will have been executed.
  • If there are any failures, refer to the execution log for details

Folder Structure
Batch File

SQL Files

Verify The Deployment
As a part of this process, we initiated by creating an Employee table with Id and Emp_Name columns in the first file. Subsequently, we inserted two rows in the second file, followed by altering a table to include an Email column in the third script. Finally, in the fourth script, we updated the employee records to include email addresses.

In SQL Server, batch scripting offers a practical means of running numerous SQL files simultaneously. Batch scripts facilitate database management operations, increase productivity, and guarantee consistency in deployment procedures by automating the execution process. Users can efficiently handle their SQL execution demands by creating and running batch scripts by following the instructions provided in this article.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.


 



SQL Server Hosting - HostForLIFE :: Knowing SQL Server's VARCHAR and NVARCHAR variables

clock April 23, 2024 08:23 by author Peter

In the realm of database management, understanding the nuances of data types is crucial for optimizing performance, storage and ensuring data integrity. When it comes to storing textual data, SQL Server offers a variety of data types, two of which are VARCHAR and NVARCHAR. While both are used for storing character data, they have significant differences that impact storage, indexing, and manipulation. In this comprehensive guide, we delve into the intricacies of VARCHAR and NVARCHAR in SQL Server, exploring their features, use cases, and performance implications.

VARCHAR
VARCHAR, short for Variable Character, is a data type used to store non-Unicode string data of variable length in SQL Server. It allocates storage only for the actual length of the data plus two bytes. The maximum storage size for VARCHAR is 8,000 bytes.
NVARCHAR

NVARCHAR, short for National Variable Character, is used to store Unicode string data of variable length. Unlike VARCHAR, NVARCHAR stores Unicode characters, allowing it to support multiple languages and character sets. It also allocates storage only for the actual length of the data plus two bytes. The maximum storage size for NVARCHAR is also 8,000 bytes.

What Sets VARCHAR and NVARCHAR Apart

Encoding of Characters

  • VARCHAR uses the underlying operating system's default code page, usually ANSI or ASCII, to store data in the database.
  • NVARCHAR uses the UTF-16 encoding technique to store Unicode data in the database. This makes it possible for NVARCHAR to support a large character set from multiple languages.

Size of Storage

  • For non-Unicode characters, VARCHAR uses one byte per character.
  • For Unicode characters, NVARCHAR takes two bytes each character.
  • For the same amount of text data, NVARCHAR takes more storage space than VARCHAR because of the Unicode encoding.

Data Range

  • Data in languages like English, Spanish, or French that do not require Unicode support can be stored using VARCHAR.
  • When working with multilingual applications or when the data may contain characters from several languages, NVARCHAR is crucial.

Performance-Related Issues

  • VARCHAR can provide marginally better performance in terms of storage and retrieval due to the smaller storage size, particularly when working with huge volumes of data.
  • NVARCHAR has a performance overhead because of its Unicode encoding and greater storage capacity. Nonetheless, on contemporary systems, this overhead is frequently insignificant, and in most situations, the advantages of Unicode support exceed the performance concerns.

Example 1. Storing English Text
Consider a scenario where you need to store the names of employees in a database table. Since the names are in English and do not require Unicode support, VARCHAR would be the appropriate choice.

CREATE TABLE dbo.Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50) );


In this example, we define the FirstName and LastName columns as VARCHAR data types with a maximum length of 50 characters each.

Example 2. Storing Multilingual Text
Now, suppose you're working on an international e-commerce platform that caters to customers from various countries, each with its own languages and character sets. In this case, using NVARCHAR would be necessary to support the diversity of languages.
CREATE TABLE dbo.Products (
ProductID INT PRIMARY KEY,
ProductName NVARCHAR(100),
Description NVARCHAR(MAX) );

Here, we define the ProductName and Description columns as NVARCHAR data types. The ProductName column stores the name of the product, while the Description column stores a detailed description. Using NVARCHAR ensures that the database can accommodate text in any language, facilitating a seamless user experience for customers worldwide.

Conclusion

VARCHAR and NVARCHAR are essential data types in SQL Server for storing character data. While VARCHAR is suitable for non-Unicode text and offers slightly better performance in terms of storage and retrieval, NVARCHAR is necessary when dealing with multilingual applications or when Unicode support is required. Understanding the differences between these data types is crucial for designing efficient database schemas and optimizing performance in SQL Server environments. By choosing the appropriate data type based on the nature of the data and the requirements of the application, developers can ensure data integrity, performance, and compatibility across different languages and character sets.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



SQL Server Hosting - HostForLIFE :: How to Renaming the Column in SQL Server ?

clock March 7, 2024 06:05 by author Peter

I recently worked on a project to assess the schema of a third-party vendor. Our organization has an internal support ticket tracking tool. The program used a SQL database, and after calculating its cost, we opted not to extend the contract. The objective was to create an in-house platform for managing internal support tickets.

My responsibility was to review the schema of the internal support database. We couldn't figure out what data was in which table because the structure was intricate and the table names were tough. Eventually, I was able to determine the relationship between tables and what data was contained in each.
I've also given the columns proper names so that we can quickly identify what data is contained in which column. I used the sp_rename method to rename tables.

This article explains how to rename a column using the sp_rename stored procedure. I also demonstrated how to rename a column in SQL Server Management Studio. First, let us look at the fundamentals of renaming a column.

The Basics of Renaming Columns
Renaming a table's column is a simple task. We can use a system-stored process called sp_rename. Additionally, we can utilize SQL Server Management Studio to rename a column. The sp_rename stored procedure can rename the following:

  • Database objects like tables, Stored procedures, and functions.
  • Indexes and statistics
  • User-defined datatypes.

In this article, we will learn how to rename any column of an SQL Server table using the sp_rename stored procedure.

How can you rename a column in SQL Server?
In SQL Server, we may rename any column or object using the sp_rename stored procedure. In this post, we'll look at how to rename columns using the sp_rename function.

The syntax for the sp_rename stored procedure is as follows.

Exec sp_rename 'original_schema_name.original_table_name.original_column_name', 'new_column_name' ,'object_type'

In the syntax

  • original_schema_name.original_table_name.original_column_name: Specify the table name whose column you want to rename. If you are renaming a column of a table that exists in the user-defined schema, you must specify the table name in three three-part names.
  • new_column_name: Specify the new name of the column.
  • object_type: Specify the object type.

Let us understand the process with simple examples. Suppose you want to rename a column of the patient table. The original column name is Address, and we want to change it to patient_address. The sp_rename command to rename the column is as follows.

USE HospitalManagementSystem
GO
EXEC sys.sp_rename 'patients.address','patient_address','COLUMN'


Once the column is renamed, let us verify that the column has been renamed successfully. You can run the below query to view the columns of the patient table.
use HospitalManagementSystem
go
select table_name,column_name from information_schema.columns where table_name='Patients'

Output

As you can see in the above image, the column Address has been changed to patient_address.

Let us take another example. Suppose you want to rename the column of Sales. invoice table which exists in the Wideworldimportors database. The current name of the column is InvoiceDate, and the new name will be InvoiceCreateDate. The query to rename the column is the following.
EXEC sys.sp_rename 'Sales.Invoices.InvoiceDate','InvoiceCreateDate','COLUMN'

Here you can see, that we are changing the column name of the invoice table which is in the Sales schema. Therefore, we have used three-part naming. Once the column is renamed, execute the following T-SQL query to verify that the column has been renamed.
select table_name,column_name from information_schema.columns where table_name='Invoices'

Output

Renaming other objects in SQL Server
The sp_rename stored procedure can be used to rename other database objects, such as indexes, constraints, and stored procedures. The syntax of the sp_rename operation stays unchanged. The object_type argument for the sp_rename column will change. Let us consider a basic example.

Assume we wish to rename the index of the sales invoice table. The index's present name is 'IX_Sales_Invoices_ConfirmedDeliveryTime', which we would like to modify to 'IX_Sales_Invoices_ConfirmedDeliveryTime_New'. In the query, the object_type argument in the sp_rename method will be set to INDEX. The query to rename the index is shown below.

EXEC sys.sp_rename 'Sales.Invoices.IX_Sales_Invoices_ConfirmedDeliveryTime','IX_Sales_Invoices_ConfirmedDeliveryTime_New','INDEX'

Once the index is renamed, you can query sys. indexes dynamic management view to verify that the index has been renamed successfully. Note that whenever we rename any index, the statistics associated with the index will be renamed as well. Here is the query to verify both changes.
SELECT object_name(object_id)[TableName], name [IndexName], Type_desc [Index Type]
FROM sys.indexes where object_id=object_id('Sales.Invoices')

Output

Using SQL Server Management Studio to Rename
We can use SQL Server Management Studio to rename the database object. In the first section, we learnt how to rename columns and indexes using the sp_rename stored procedure.

In this example, we'll see how to rename a constraint in SQL Server Management Studio. For demonstration, I'll rename the constraint in the Sales.invoice table. The present constraint name is DF_Sales_Invoices_InvoiceID, which we will rename to Default_Sales_Invoices_InvoiceID. As the name implies, this constraint is a default constraint.

First, launch SQL Server Management Studio and connect to your database server. Expand databases. Expand the Wideworldimportors database.

A database contains many tables. Expand the Sales, Invoice, and Constraint tables. Press F2 or right-click on DF_Sales_Invoices_InvoiceID and choose Rename.

The name will be editable. Change the name to Default_Sales_Invoices_InvoiceID and hit enter. The name will be changed. The SQL Server management studio prompts a confirmation message that looks like the following image.

Click OK to change the name. Once changes are made, execute the following T-SQL query to verify that the constraint has been renamed successfully.
SELECT
  [constraint].name AS constraint_name,
  OBJECT_NAME([constraint].parent_object_id) AS table_name,
  [column].name AS column_name from
  sys.default_constraints [constraint]
JOIN
  sys.columns [column] ON [constraint].parent_object_id = [column].object_id
    AND [constraint].parent_column_id = [column].column_id
    where  OBJECT_NAME([constraint].parent_object_id)='Invoices'

Output

Let us take a look at some limitations and things to be considered before renaming any column.

Limitations and Considerations

If you are renaming any column in a table or renaming any object in a database, you must consider the following limitations and possible issues that might break the application.

  • ALTER permission is needed on the object that you want to rename. Suppose you want to rename a column name; you must have ALTER object permission on the table whose column you are renaming.
  • Renaming a column name always breaks the stored procedure or other objects (View, function, etc.) that are referencing that column. For example, you are renaming a column that is being used in a view. Therefore, make sure you modify all the stored procedures, functions, and triggers that reference the column that was renamed. You can use sys.sql_expression_dependencies to find all dependencies of the column.
  • When you rename a stored procedure, the object's name in sys.sql_modules will not change. Hence Microsoft recommends dropping and recreating an object instead of just renaming it.
  • When you rename a column of a table that is part of replication, the replication might break so if we want to rename the column of the replicated table, first, we must pause the replication, then rename the column using sp_rename or SQL Server management studio, update all database objects that are referencing the column, and finally, reinitialize replication with the new snapshot.

Conclusion
In this tutorial, we learned how to rename any column in a table. I demonstrated how to rename a column using a system-stored process called sp_rename, complete with syntax and easy examples. We also learned how to rename a column using SQL Server Management Studio. We can also use other tools, such as dbForge Studio for SQL Server, to run the stored procedure to rename a column. We also reviewed the limits and other difficulties that must be addressed before to renaming any object or column.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



SQL Server Hosting - HostForLIFE :: What Distinguishes UNION from UNION All (SQL Server)?

clock February 13, 2024 06:18 by author Peter

While UNION ALL combines them without removing duplicates, yielding faster results but keeping all rows, including duplicates, UNION merges and filters out duplicates from different SELECT queries.

Now let's look at the example.

I have started by making two tables, Employee and Employee_One.

CREATE TABLE Employee
(
 employeeId INT IDENTITY(1,1) PRIMARY KEY,
 employeeName VARCHAR(50),
 City VARCHAR(100)
)

The Employee table has records as follows.

CREATE TABLE Employee_One
(
 employeeId INT IDENTITY(1,1) PRIMARY KEY,
 employeeName VARCHAR(50),
 City VARCHAR(100)
)


The Employee_One table has records as follows.

Let's explore how the UNION operation works.

SELECT City
FROM Employee
UNION
SELECT City FROM Employee_One

Employee table records

Employee_One table records

After using UNION between these two tables, we will get results as follows (removing duplicates).

In conclusion, the UNION function in SQL Server automatically eliminates duplicate rows while combining the output of several SELECT queries to create a single, cohesive result set. Let's examine the operation of UNION ALL.

SELECT City

FROM Employee

UNION ALL

SELECT City

Employee_One

Employee table records

Employee_One table records

Employee_One table records

After using UNION ALL between these two tables, we will get results as follows (including all records - without removing duplicate records).
UNION ALL

In summary
In SQL Server, the UNION ALL method is used to aggregate the output of several SELECT queries without removing duplicate rows. Because duplicate elimination processing is not present in UNION, UNION ALL offers faster performance than UNION and contains all records from the combined queries, making it a good option when maintaining duplicate entries is required.

I hope this post has given you useful knowledge on using UNION and UNION ALL in SQL Server. Best wishes for the future.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.


 



SQL Server Hosting - HostForLIFE :: Most Common MS SQL Server SQL Queries

clock December 11, 2023 07:15 by author Peter

Overview
Microsoft SQL Server is a well-known and potent relational database solution in the field of database management. During their exploration of the complex world of SQL, developers and database administrators often find themselves returning to the same questions in both interviews and practical situations.

We'll explore the most commonly asked SQL questions for MS SQL Server in this blog, offering tips and code samples to help novices and experts alike.

Retrieving Data. The SELECT Statement
The foundation of any database interaction lies in retrieving data. The SELECT statement is your go-to tool for this task.
-- Retrieve all columns from a table
SELECT * FROM TableName;

-- Retrieve specific columns
SELECT Column1, Column2 FROM TableName;

-- Filter data with WHERE clause
SELECT * FROM TableName WHERE Condition;


Filtering and Sorting Data
Refining data based on conditions and sorting results is a common requirement.
-- Filtering with WHERE
SELECT * FROM TableName WHERE Column = 'Value';

-- Sorting with ORDER BY
SELECT * FROM TableName ORDER BY Column ASC/DESC;


Aggregating Data. GROUP BY and Aggregate Functions
Aggregating data provides valuable insights into summaries and statistics.
-- Grouping data with GROUP BY
SELECT Column, COUNT(*)
FROM TableName
GROUP BY Column;

-- Using Aggregate Functions
SELECT AVG(Column), SUM(Column), MAX(Column)
FROM TableName
WHERE Condition;


Joining Tables. INNER JOIN, LEFT JOIN
When data resides in multiple tables, joining becomes essential.
-- Inner Join
SELECT *
FROM Table1
INNER JOIN Table2 ON Table1.ID = Table2.ID;

-- Left Join
SELECT *
FROM Table1
LEFT JOIN Table2 ON Table1.ID = Table2.ID;


Subqueries. Nesting Queries for Precision
Subqueries enable embedding one query within another, offering precision and flexibility.
-- Using Subqueries
SELECT *
FROM TableName
WHERE Column IN (SELECT Column FROM AnotherTable WHERE Condition);


Modifying Data. UPDATE and DELETE Statements
Ensuring data accuracy involves updating and deleting records.
-- Update Statement
UPDATE TableName SET Column = 'NewValue' WHERE Condition;

-- Delete Statement
DELETE FROM TableName WHERE Condition;


Transaction Control. BEGIN, COMMIT, ROLLBACK
Transactions maintain data integrity by grouping operations.
-- Begin Transaction
BEGIN TRANSACTION;

-- Commit Transaction
COMMIT;

-- Rollback Transaction
ROLLBACK;


Working with Dates. Date Functions
Manipulating dates is a common task, and SQL Server provides robust date functions.
-- Get Current Date
SELECT GETDATE();

-- Extract Part of a Date
SELECT YEAR(DateColumn), MONTH(DateColumn), DAY(DateColumn);


Common Table Expressions (CTEs). Enhancing Readability
CTEs simplify complex queries and enhance code readability.
-- Using CTE
WITH MyCTE AS (
    SELECT Column FROM TableName WHERE Condition
)
SELECT * FROM MyCTE;


Window Functions. Analytical Insights
Window functions offer advanced analytical capabilities.
-- Using Window Function
SELECT Column, ROW_NUMBER() OVER (ORDER BY Column) AS RowNum
FROM TableName;


These SQL queries encapsulate the essence of database interactions and form the backbone of database-related interviews and projects. Mastering these queries empowers professionals to navigate diverse scenarios efficiently.
Conclusion

The world of SQL Server queries is vast, and continuous learning is key.

As you embark on your SQL journey, these fundamental queries will serve as the stepping stones to deeper insights and mastery. Happy querying!

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.


 



SQL Server Hosting - HostForLIFE :: In SQL Server, How Can I obtain Every Job for an Agent?

clock December 6, 2023 06:59 by author Peter

How to Acquire Every SQL An essential part of Microsoft SQL Server is SQL Server Agent, which lets database administrators utilize jobs to automate a variety of processes like data processing, backup, and maintenance. You can arrange for these jobs to execute at predetermined times, which will simplify the management and upkeep of your SQL Server system. This post will demonstrate how to use SQL Server Management Studio (SSMS) to get a list of all SQL Server Agent jobs.

Finding Jobs for SQL Server Agents

To obtain a list of every SQL Server Agent job in SSMS, take the following actions:

Step 1: Establish a connection with SQL ServerWorks with Server Agents?
To access your SQL Server instance, open SQL Server Management Studio.

Step 2: Launch the SQL Server Agent
Open SSMS and select the "Object Explorer" window from the menu on the left. The "SQL Server Agent" node can be seen by expanding the server node. Click "SQL Server Agent" with a right-click, then choose "Jobs."

Step 3. View Job List
Once you've selected "Jobs," the right-hand pane will display a list of all the SQL Server Agent jobs configured on the SQL Server instance. The list includes the following columns:
    Job ID
    Job Name
    Owner
    Enabled (whether the job is currently enabled or not)
    Last Run Date
    Next Run Date
    Last Run Outcome

You can see an overview of the jobs, their statuses, and when they were last run, making it easier to manage your SQL Server Agent jobs.

Step 4: Job Specifics
To see additional information about a particular job, right-click on the job name and choose "Properties." This will cause a new window to open, displaying a plethora of job-related information such as the timetable, steps, and notifications.
Using Query, Retrieve SQL Server Agent Jobs

The msdb database contains information on SQL Server Agent jobs. SQL queries can be used to obtain job details, their steps, and other pertinent data. The two main tables that we will be utilizing are sysjobs and sysjobsteps. This is an extensive SQL query that retrieves different information on SQL Server Agent jobs.

SELECT
    [sJOB].[job_id] AS [JobID]
    , [sJOB].[name] AS [JobName],
    case when d.name is null then 'No Schedule' else d.name end Schedule,
isnull (case d.freq_type
when '1 ' then 'Once'
when '4' then 'Daily'
when '8' then 'Weekly'
when '16' then 'Monthly'
when '32' then 'Monthly relative'
when '64' then 'When SQL Server Agent starts' end, 'None') as Frequency,
     CASE
        WHEN [sJOBH].[run_date] IS NULL OR [sJOBH].[run_time] IS NULL THEN NULL
        ELSE CAST(
                CAST([sJOBH].[run_date] AS CHAR(8))
                + ' '
                + STUFF(
                    STUFF(RIGHT('000000' + CAST([sJOBH].[run_time] AS VARCHAR(6)),  6)
                        , 3, 0, ':')
                    , 6, 0, ':')
                AS DATETIME)
      END AS [LastRunDateTime]
    , CASE [sJOBH].[run_status]
        WHEN 0 THEN 'Failed'
        WHEN 1 THEN 'Succeeded'
        WHEN 2 THEN 'Retry'
        WHEN 3 THEN 'Canceled'
        WHEN 4 THEN 'Running' -- In Progress
      END AS [LastRunStatus]
    , STUFF(
            STUFF(RIGHT('000000' + CAST([sJOBH].[run_duration] AS VARCHAR(6)),  6)
                , 3, 0, ':')
            , 6, 0, ':')
        AS [LastRunDuration]
    , [sJOBH].[message] AS [LastRunStatusMessage]
    , CASE [sJOBSCH].[NextRunDate]
        WHEN 0 THEN NULL
        ELSE CAST(
                CAST([sJOBSCH].[NextRunDate] AS CHAR(8))
                + ' '
                + STUFF(
                    STUFF(RIGHT('000000' + CAST([sJOBSCH].[NextRunTime] AS VARCHAR(6)),  6)
                        , 3, 0, ':')
                    , 6, 0, ':')
                AS DATETIME)
      END AS [NextRunDateTime],
      isnull (convert (varchar,d.Date_Created), 'None') CreatedDate
FROM
    [msdb].[dbo].[sysjobs] AS [sJOB]

    LEFT JOIN (
                SELECT
                    [job_id]
                    , MIN([next_run_date]) AS [NextRunDate]
                    , MIN([next_run_time]) AS [NextRunTime]
                FROM [msdb].[dbo].[sysjobschedules]
                GROUP BY [job_id]
            ) AS [sJOBSCH]
        ON [sJOB].[job_id] = [sJOBSCH].[job_id]
    LEFT JOIN (
                SELECT
                    [job_id]
                    , [run_date]
                    , [run_time]
                    , [run_status]
                    , [run_duration]
                    , [message]
                    , ROW_NUMBER() OVER (
                                            PARTITION BY [job_id]
                                            ORDER BY [run_date] DESC, [run_time] DESC
                      ) AS RowNumber
                FROM [msdb].[dbo].[sysjobhistory]
                WHERE [step_id] = 0
            ) AS [sJOBH]
        ON [sJOB].[job_id] = [sJOBH].[job_id]
        AND [sJOBH].[RowNumber] = 1
        left outer join msdb.dbo.sysjobschedules e on e.job_id = [sJOB].job_id
        left outer join msdb.dbo.sysschedules d on e.schedule_id = d.schedule_id


The msdb.dbo.sysjobs table contains information about SQL Server Agent jobs.
The msdb.dbo.sysjobsteps table contains information about the steps within those jobs.
We use the inner join clause to link the two tables based on the job_id column.

In summary
Monitoring and controlling automated processes in a SQL Server environment requires retrieving information about SQL Server Agent jobs. With the SQL query that is provided, you may get comprehensive details on jobs and the steps that go along with them. Database administrators can maintain the functionality and health of their SQL Server instances by routinely accessing and evaluating this data. Furthermore, by utilizing this data, job-related problems can be resolved and work schedules can be optimized for increased productivity.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server Hosting - HostForLIFE :: What exactly is logical read in SQL?

clock December 1, 2023 07:04 by author Peter

SQL logical read
When the query engine needs to access data, it performs a logical read. It first verifies SQL Server's in-memory storage. If the relevant page is already present in SQL Server's memory, it is used. If the data page is not discovered in memory, a physical read is initiated, which results in the retrieval of the data page from the disk. A "cache hit" is a logical read without a following physical read.

For query resolution, the buffer cache, also known as the buffer pool, acts as SQL Server's primary working memory. The amount of RAM allocated to SQL Server has a direct impact on the size of the accessible buffer cache.

It is nearly impossible to provide particular recommendations without first reviewing the query, comprehending the table content, data structure, and indexing.

While a large number of logical readings is not necessarily harmful, an excessive number of logical reads is. For example, if a query returns only three rows of data but requires scanning through 200 million rows of data, the process becomes inefficient and can be improved by query optimization or the insertion of an appropriate index.

Example of a query

select *
from
(
  select *
  from Employees
  where empId = 9
)
where deptId = 1;

You can combine both criteria in a single step to improve the query and reduce logical reads. Rather of selecting all employees with empid 9 and then filtering for deptid 1, you may combine both requirements in the initial SELECT statement. This method seeks to reduce the size of the intermediate result set while increasing query efficiency.

Here's an example of how you might change the query:

SELECT *
FROM employees
WHERE empid = 9 AND deptid = 1;

When both conditions are combined in a single WHERE clause, the query engine is more likely to execute a more efficient execution plan, potentially resulting in fewer logical reads than in the two-step procedure. The efficiency of this optimization, however, is dependent on the specific database schema, indexes, and SQL Server's query optimizer.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server Hosting - HostForLIFE :: SQL IDENTITY and SCOPE_IDENTITY() Decoded

clock November 13, 2023 08:26 by author Peter

The maintenance of identity columns is critical in SQL databases for maintaining data integrity. After an INSERT operation, two often used functions, @@IDENTITY and SCOPE_IDENTITY(), aid in recovering recently produced identity data. Understanding the distinctions between these two is critical for database administrators and developers.

What exactly is @@IDENTITY?

@@IDENTITY is a global SQL Server variable that stores the most recent identity value generated during the current session across all tables with identity columns. While it may appear to be useful, it is crucial to realize that @@IDENTITY may not always yield the correct value. @@IDENTITY may capture the most recent identity value from any table in scenarios involving triggers or additional operations that create new tables with identity columns, potentially resulting in inaccurate results.

What exactly is SCOPE_IDENTITY()?
To alleviate the restrictions of @@IDENTITY, SQL Server provides SCOPE_IDENTITY(), a method built expressly to address identity column retrieval difficulties. SCOPE_IDENTITY() returns the most recently generated identity value within the current scope or session, making it a more dependable and accurate method of retrieving the recently inserted identity value.

Recommended Practices
When working with identity columns and needing to capture newly generated identity values after an INSERT operation, SCOPE_IDENTITY() is highly recommended. Unlike @@IDENTITY, SCOPE_IDENTITY() verifies the accuracy of the obtained identity value, avoiding potential conflicts caused by triggers or concurrent actions.

Conclusion
In conclusion, while @@IDENTITY may appear to be a convenient way to acquire the most recent identity value, its instability in certain contexts can result in unexpected results. SCOPE_IDENTITY(), on the other hand, provides a more secure and dependable method of retrieving the most recently created identity value within the current scope or session. Choosing between @@IDENTITY and SCOPE_IDENTITY() is critical for proper identity column retrieval and maintaining data consistency in SQL databases.

Understanding the difference between @@IDENTITY and SCOPE_IDENTITY() enables developers to manage identity columns with confidence and get accurate identity values, contributing to a more robust and dependable database environment.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



SQL Server Hosting - HostForLIFE :: SQL Server Dynamic Data Masking

clock October 25, 2023 08:52 by author Peter

What exactly is Dynamic Data Masking?
Dynamic Data Masking (DDM) is a SQL Server security feature that helps secure sensitive data in real time by obscuring it from users who do not have the necessary access rights. It enables users to selectively mask sensitive data without changing the underlying data. This aids in data privacy and confidentiality protection in contexts where sensitive data is accessed by different people with varying levels of clearance.

This post will go over the concept of Dynamic Data Masking in SQL Server, as well as its benefits and examples.

How may Dynamic Data Masking be used?

  • DDM can be used with one of four masking functions: default, email, random, or custom. These functions enable you to modify how the data is masked based on the data type and sensitivity level.
  • Default Masking: Use the default masking function to mask sensitive data with a predetermined mask. For example, you can utilize the default masking mechanism to hide all but the final four digits of a credit card number.
  • Email Masking: When you wish to mask an email address but keep it recognizable as an email address, you utilize the email masking function. For example, you can utilize the email masking tool to hide an email address's domain name.
  • When you want to mask data with a random value, you use the random masking function. You can, for example, use the random masking function to replace a year in Date of Birth with a random value.
  • Custom Masking: Use the custom masking function to build a bespoke mask for sensitive data. You can, for example, utilize the custom masking function to mask a phone number in a specific format.

How to create Masking functions?
Let's see, with an example, create a table with default, email, random, and custom masking functions and insert some records by running the following command.

--Create table with masking functions
CREATE TABLE dbo.DDM_TestTable(
    Id        INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    FirstName VARCHAR(100) MASKED WITH (FUNCTION = 'PARTIAL(1, "xxx", 1)') NULL,
    LastName  VARCHAR(100) NOT NULL,
    Phone     VARCHAR(10) MASKED WITH (FUNCTION = 'DEFAULT()') NULL,
    Email     VARCHAR(100) MASKED WITH (FUNCTION = 'EMAIL()') NOT NULL,
    BirthYear SMALLINT MASKED WITH (FUNCTION = 'RANDOM(1000, 9999)') NULL
    );

--Inser sample records
INSERT INTO dbo.DDM_TestTable (FirstName, LastName, Phone, Email, BirthYear)
VALUES ('Peter', 'Black', '9876543210', '[email protected]', 1982),
('Scott', 'Cassidy', '9128374650', '[email protected]', 1991),
('John', 'Lee', '9021873456', '[email protected]', 1989),
('Laura', 'M', '8907654321', '@hostforlife.eu">[email protected]', 1985);


Create a User and Grant the SELECT permission on the schema where the table resides by execution the following command.
CREATE USER DDMUser WITHOUT LOGIN;
GRANT SELECT ON SCHEMA::dbo TO DDMUser;

Execute the query as the DDMUser to view masked data from the table.
EXECUTE AS USER = 'DDMUser'
SELECT * FROM dbo.DDM_TestTable


Benefits of Dynamic Data Masking

Organizations that need to protect sensitive data might benefit from Dynamic Data Masking in a variety of ways. Some of these advantages.

  • Enhanced Security: Dynamic Data Masking shields sensitive data from unauthorized users by obscuring it. This aids in the prevention of data breaches and illegal access to critical information.
  • Improved Compliance: Many firms must adhere to data privacy standards such as GDPR and HIPAA. Dynamic Data Masking assists enterprises in complying with these rules by preventing unauthorized access to sensitive data.
  • Reduced danger: Dynamic Data concealing decreases the danger of data theft and other security breaches by concealing sensitive data. This helps to defend the organization's reputation and sustain customer trust.
  • Increased Flexibility: Dynamic Data Masking can be used to mask data selectively based on user roles and permissions. This allows for more control over access to sensitive data.

What new DDM feature was introduced in SQL Server 2022(16.x)?
Datetime has a new masking function.
With the introduction of granular permission, we may grant or revoke UNMASK permission to a user or database role at the database, schema, table, or column level.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in