Quantcast
Channel: Welcome To TechBrothersIT
Viewing all 1874 articles
Browse latest View live

What is Check Constraint in SQL Server - SQL Server / TSQL Tutorial Part 82

$
0
0

What is Check Constraint : 

Check Constraints limit the values that are accepted by one or more columns.


Let's understand Check Constraint with real time scenario. 

You are working as SQL Server developer, You need to create dbo.Customer table which should have columns such as FName, LName and Address. As FName is going be be VARCHAR so the users can insert string values that can contain alphabets, numeric and other characters. You want to write a Check Constraint so FName only accepts alphabets.

Solution:

Let's create the table with Check Constraint by using below script

--Create Table with 
use YourDatabaseName
go
Createtable dbo.Customer
(
FName
VARCHAR(100) NotNull,
LName
VARCHAR(100),
StreetAddress
VARCHAR(255),
Check (FName notlike'%[^a-z]%')
)

Let's insert some records in table and see if our Check Constraint is working as expected. It should let only insert those records in which FName only contains alphabets.

--insert some sample records
insertinto dbo.Customer
(FName,LName,StreetAddress)
Values ('Aamir','Shahzad','xyz address')
go
insertinto dbo.Customer
(FName,LName,StreetAddress)
Values ('Aamir4','Shahzad','xyz address')
go
insertinto dbo.Customer
(FName,LName,StreetAddress)
Values ('abc3c','Shahzad','xyz address')
go
insertinto dbo.Customer
(FName,LName,StreetAddress)
Values ('-tName','Shahzad','xyz address')
When I executed above insert scripts, below are the messages I received from SQL Server.

(1 row(s) affected)
Msg 547, Level 16, State 0, Line 18
The INSERT statement conflicted with the CHECK constraint "CK__Customer__FName__5FB337D6". The conflict occurred in database "YourDatabaseName", table "dbo.Customer", column 'FName'.
The statement has been terminated.
Msg 547, Level 16, State 0, Line 22
The INSERT statement conflicted with the CHECK constraint "CK__Customer__FName__5FB337D6". The conflict occurred in database "YourDatabaseName", table "dbo.Customer", column 'FName'.
The statement has been terminated.
Msg 547, Level 16, State 0, Line 26
The INSERT statement conflicted with the CHECK constraint "CK__Customer__FName__5FB337D6". The conflict occurred in database "YourDatabaseName", table "dbo.Customer", column 'FName'.
The statement has been terminated.

It only inserted very first record that contains all alphabets for FName, rest of the records are rejected by our Check Constraint as they contain other characters than alphabets.

Let's check the data in table to make sure only single record is inserted.
What is Check Constraint in SQL Server and how to Create Check Constraint in SQL Server



How to Create Check Constraint on Single Column in SQL Server - SQL Server / TSQL Tutorial Part 83

$
0
0

Scenario : 

You are working as SQL Sever developer, You are preparing scripts to create Tables in database. As part of these scripts you need to create Check Constraints but you want to follow the company's naming standards for Check Constraints. How would you add Check Constraint Name in your scripts.

Solution:

SQL Server automatically give name to Check Constraint if we don't provide. Let's execute the below script and see what name SQL Server assign to Check Constraint when we don't provide the name. In below example we are creating Check Constraint on FName and making sure it only accepts alphabets.

--Create Table with Check Constraint
use YourDatabaseName
go
Createtable dbo.Customer
(
FName
VARCHAR(100) NotNull,
LName
VARCHAR(100),
StreetAddress
VARCHAR(255),
Check (FName notlike'%[^a-z]%')
)

We can use system views to gather information related to Check Constraints.
--How to get Check Constraints in SQL Server
SELECT
*
FROM INFORMATION_SCHEMA.Check_Constraints

How to create Check Constraint in SQL Server with default Name

Let's say that the name SQL Server provided to Check Constraint is not according to our company standards. Our standards say that the Check Constraint should follow below pattern
Start with Chk_SchemaName_TableName_ColumnName_CheckConstraintDescription.  To add a Check Constraint  , your syntax will be
Constraint Constraint_Name Check LogicForCheckConstraint.

--Create Table with Check Constraint 
use YourDatabaseName
go
Createtable dbo.Customer
(
FName
VARCHAR(100) NotNull,
LName
VARCHAR(100),
StreetAddress
VARCHAR(255),
Constraint Chk_dbo_Customer_FName_AlphabetsOnly
Check (FName notlike'%[^a-z]%')

)

Run the select query on system view to get Check Constraint information. I suggest to create objects with some naming convention or standards instead of letting the sql server decide name for your objects.
How to create Check Constraint by providing name according to your company standards in SQL Server

How to Create Check Constraint on Multiple Columns in SQL Server - SQL Server / TSQL Tutorial Part 84

$
0
0

Scenario:

You are working as SQL Server developer, you need to create dbo.Customer table that should have First Name, Age and Age Type columns. You can add CustomerId as Identity. You need to create Check Constraint on Age and Age Type Columns with below logic


<65 agetype="Adult" and="" p="">
If true then let the record insert or update otherwise fail due to Check Constraint.

Solution:
Below script can be used to add Check Constraint on multiple columns according to our requirement.

65>
CREATETABLE dbo.Customer (
CustomerId INTidentity(1, 1)
,NAME VARCHAR(100)
,Age INT
,AgeType VARCHAR(15)
,CONSTRAINT dbo_Customer_AgeAndAgeType CHECK (
(
Age <= 17
AND AgeType = 'Child'
)
OR (
Age > 17
AND Age < 65
AND AgeType = 'Adult'
)
OR (
Age >= 65
AND AgeType = 'Senior'
)
)

)

Let's insert few records and try to see if Check Constraint is working as expected.



--Correct values accrording to Constraint
insertinto dbo.Customer(Name,Age,AgeType)
Values('Najaf',13,'Child')
go

--Wrong values according to Check Constraint
insertinto dbo.Customer(Name,Age,AgeType)
Values('Leena',14,'Adult')
go
--Correct values accroding to Constraint
insertinto dbo.Customer(Name,Age,AgeType)
Values('Raza',30,'Adult')
go
--Wrong values according to Check Constraint
insertinto dbo.Customer(Name,Age,AgeType)
Values('Aamir',30,'Senior')
go
--Wrong values according to Check Constraint
insertinto dbo.Customer(Name,Age,AgeType)
Values('John',65,'Adult')
go
--Correct values accroding to Constraint
insertinto dbo.Customer(Name,Age,AgeType)
Values('Kris',65,'Senior')
go


(1 row(s) affected)
Msg 547, Level 16, State 0, Line 25
The INSERT statement conflicted with the CHECK constraint "dbo_Customer_AgeAndAgeType". The conflict occurred in database "YourDatabaseName", table "dbo.Customer".
The statement has been terminated.

(1 row(s) affected)
Msg 547, Level 16, State 0, Line 33
The INSERT statement conflicted with the CHECK constraint "dbo_Customer_AgeAndAgeType". The conflict occurred in database "YourDatabaseName", table "dbo.Customer".
The statement has been terminated.
Msg 547, Level 16, State 0, Line 37
The INSERT statement conflicted with the CHECK constraint "dbo_Customer_AgeAndAgeType". The conflict occurred in database "YourDatabaseName", table "dbo.Customer".
The statement has been terminated.

(1 row(s) affected)

Let's check the data in table by using select query. As can be seen below the only records are inserted which passed the Check Constraint. Rest of the records could not be inserted.
How to create Check Constraint on Multiple Columns in SQL Server Table

 Let's try to update the records and see if Check Constraint is working as expected.

update dbo.Customer
set Age=30
where Customerid=1


It failed with below error as we can not have Age 30 for AgeType='Child' according to our Check Constraint logic.

Msg 547, Level 16, State 0, Line 18
The UPDATE statement conflicted with the CHECK constraint "dbo_Customer_AgeAndAgeType". The conflict occurred in database "YourDatabaseName", table "dbo.Customer".
The statement has been terminated.

How to get list of all Check Constraints in SQL Server Database - SQL Server / TSQL Tutorial Part 85

$
0
0

Scenario:

You are working as SQL Server developer, you need to provide the query that should return list of all the Check Constraint in SQL Server database.

Solution:

We can use different system objects to get this information.

--List Check Constraints in Database
SELECT DB_Name() AS DBName
,Schema_Name(Schema_id) AS TableSchema
,Object_name(parent_object_id) AS TableName
,o.NAME AS ConstraintName
FROM sys.objects o
WHERE type_desc = 'CHECK_CONSTRAINT'


How to get list of Check Constraints in SQL Server Database


If you are interested to get definition of Check Constraints with table name, you can use below query.


--Get Check Constraints in Database with Definition
SELECT DB_Name() AS DBName
,Schema_Name(Schema_id) AS TableSchema
,Object_name(parent_object_id) AS TableName
,DEFINITION
FROM sys.check_constraints


How to get list of Check Constraints with definition in SQL Server Database


How to get List Enabled / Disabled Check Constraint in SQL Server Database - SQL Server / TSQL Tutorial Part 86

$
0
0

Scenario:

You are working as SQL Server Developer and you are asked to provide list of all Check Constraint with status if enabled or disabled.

Solution:

The below query can be used to get the list of all Check Constraints from a database with status if they are enabled or disabled in SQL Server Database.

--Get List of Enabled / Disabled Check Constraints
SELECT DB_Name() AS DBName
,Schema_Name(Schema_id) AS TableSchema
,Object_name(parent_object_id) AS TableName
,DEFINITION
,CASE
WHEN is_disabled = 0
THEN'NO'
ELSE'YES'
ENDAS IsDisabled
FROM sys.check_constraints


How to get list of Enabled or Disabled Check Constraints in SQL Server Database

How to disable all Check Constraints in SQL Server Database - SQL Server / TSQL Tutorial Part 87

$
0
0

Scenario:

You are working as SQL Server / ETL developer. You need to load bunch of data to tables in SQL Server Database. Check Constraints are created on different tables. There are chances that the data you are going to load will not qualify according to Check Constraint. The business want you to load the data anyways even it does not qualify with Check Constraint. You want to temporary disable all the constraints in SQL Server database and then load the data and then re-enabled the Check Constraints.


Solution:

The below script can be used to generate Disable Check Constraint script for all the Check Constraints which are enabled in database. You can further filter the tables in where clause if you don't want to generate script for all the tables.


--Generate Script to Disable All Check Constraint in SQL Server Database
Select DB_Name() AS DBName,
Schema_Name(Schema_id) AS TableSchema,
Object_name(parent_object_id) as TableName,
definition,
'Alter Table [' + Schema_Name(Schema_id)
+ '].[' + Object_name(parent_object_id)
+ ']' + ' NOCHECK CONSTRAINT '
+ '[' + NAME + ']'AS DisableCheckConstraint
From sys.check_constraints
where is_disabled=0

How to generate scripts to Disable all Check Constraints in SQL Server Database
Copy the results from DisableCheckConstraint column and run in SSMS to disable required Check Constraints.

ALTERTABLE [dbo].[Customer22]NOCHECKCONSTRAINT [CK__Customer2__FName__6C190EBB]

ALTERTABLE [dbo].[Employee] NOCHECKCONSTRAINT [CK__Employee__FName__7A672E12]

How to Enable all Check Constraints in SQL Server Database - SQL Server / TSQL Tutorial Part 88

$
0
0

Scenario:

You are working as SQL Server developer or ETL developer, You disabled all the Check Constraints in SQL Server Database before loading data. You need to provide the script that should be able to generate the enable Check Constraint scripts for all the Check Constraints which are disabled in SQL Server Database.

Solution:

We can use system objects to generate enable Check Constraints scripts. Below query can be used to generate scripts to Enable Check Constraints, If you don't want to enable all Check Constraints you can further filter the objects in where clause.

--Generate Script to Enable All Check Constraint in SQL Server Database
Select DB_Name() AS DBName,
Schema_Name(Schema_id) AS TableSchema,
Object_name(parent_object_id) as TableName,
definition,
'Alter Table [' + Schema_Name(Schema_id)
+ '].[' + Object_name(parent_object_id)
+ ']' + ' CHECK CONSTRAINT '
+ '[' + NAME + ']'AS EnableCheckConstraint
From sys.check_constraints
where is_disabled=1

How to generate Enable all Check Constraints Script in SQL Server Database
Copy the results from EnableCheckConstraint column, paste in SSMS and execute.

AlterTable [dbo].[Customer22] CHECKCONSTRAINT [CK__Customer2__FName__6C190EBB]
AlterTable [dbo].[Employee] CHECKCONSTRAINT [CK__Employee__FName__7A672E12]

The ALTER TABLE statement conflicted with the CHECK constraint in SQL Server - SQL Server / TSQL Tutorial Part 89

$
0
0

Scenario:

You are working as SQL Server developer, you are asked to add Check Constraint to one existing table dbo.Employee on FName column and write logic for Check Constraint so it should always accept alphabets.

When you tried to add Check Constraint, you got below error.

Msg 547, Level 16, State 0, Line 19
The ALTER TABLE statement conflicted with the CHECK constraint "Chk_dbo_Employee_FName". 
The conflict occurred in database "YourDatabaseName", table "dbo.Employee", column 'FName'.

Solution:

Let's generate the scenario first for the error. Create sample dbo.Employee table with some sample data.

--Create Table  
use YourDatabaseName
go
Createtable dbo.Employee
(
FName
VARCHAR(100) NotNull,
LName
VARCHAR(100),
StreetAddress
VARCHAR(255)
)
--Insert data in sql table
insertinto dbo.Employee(FName,LName,StreetAddress)
values ('Aamir','Shahzad','xyz address')
go
insertinto dbo.Employee(FName,LName,StreetAddress)
values ('Raza A',Null,'abc address')
go

Now run the alter table statement to add Check Constraint.  Once you will execute this statement you will get above error. as existing data does not qualify for Check Constraint. We have space in first name for 'Raza A' and our Check Constraint says that the data in FName should be always alphabets.

Altertable dbo.Employee
AddConstraint Chk_dbo_Employee_FName
Check (FName notlike'%[^a-z]%')
1) First Solution: Correct Existing Data
Fist solution can be, you find the data that does not qualify for Check Constraint and correct that and then add Check Constraint.

2) If business don't want to fix the existing data and want to implement Check Constraint from moving forward, you can create the Check Constraint with Nocheck. By doing that it will not validate existing data against our Check Constraint rule but only apply to new data.

Altertable dbo.Employee withnocheck
AddConstraint Chk_dbo_Employee_FName
Check (FName notlike'%[^a-z]%')
Let's insert couple of records and check if our Constraint is working as expected.

insertinto dbo.Employee(FName,LName,StreetAddress)
values ('Test 123',Null,'test address')
go

insertinto dbo.Employee(FName,LName,StreetAddress)
values ('Najaf',Null,'test address')
go
The first insert will fail as it does not qualify with our Check Constraint rule. Second record will be inserted successfully. Let's check the data in table now.

How to add Check Constraint to Column with Existing Data in SQL Server 



The identifier that starts with '' is too long. Maximum length is 128.- SQL Server Error

$
0
0

Scenario:

You are working as SQL Server developer or ETL Developer, One of your SSIS Package automatically generate the tables after reading the column name from your flat files and load the data. but you received below error when it was trying to create a table from a file.

Msg 103, Level 15, State 4, Line 39
The identifier that starts with '' is too long. Maximum length is 128.


Solution:

SQL Server allows only 128 characters for identifiers such as Stored Procedure name, Table Name, Column Name etc..
If we try to create an object with name of more than 128 characters, we get error.

--By using Replicate, generate 124 Character string
Select replicate('O',129)

--Create dbo.Customer table with Column of 128 Character length
Createtable dbo.Customer
(OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO int)
go

--Create a Stored Procedure of name of 128 character length
CreateProcedure OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
as
BEGIN
Select 2
END


Msg 103, Level 15, State 4, Line 42
The identifier that starts with 'OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' is too long. Maximum length is 128.
Msg 103, Level 15, State 4, Line 46
The identifier that starts with 'OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' is too long. Maximum length is 128.



To solve this issue, simply we have to fix the length of our object names . If we are getting the files to load into sql server for which we have to create the tables dynamically by reading the column name, we need to make sure the column name length is no more than 128 characters.

What is Default Constraint in SQL Server - SQL Server / TSQL Tutorial Part 90

$
0
0

What is Default Constraint in SQL Server :

Default Constraint inserts the default value into a column when you do not provide value for column. 

Let's understand by using below examples.

Scenario:

Let's say you need to create a dbo.Customer table with First Name, Last Name, Country Name and Region. If the user does not provide the values for Country Name and Region Columns you always want to insert Country Name='USA' and for Region='North America'. 

The below script can be used to create Default Constraint for Country Name and Region columns.


USE YourDatabaseName
GO
CREATETABLE dbo.Customer (
FirstName
VARCHAR(50)
,LastName
VARCHAR(50)
,CountryName VARCHAR(50) DEFAULT'USA'
,Region VARCHAR(50) DEFAULT'North America'

)


Now insert couple of records by provide values for all the columns by using below insert statements.

--Insert some sample data by provided CountryName and Region
Insertinto dbo.Customer (FirstName,LastName,CountryName,Region)
Values('Aamir','Shahzad','Pakistan','Asia')
go
Insertinto dbo.Customer (FirstName,LastName,CountryName,Region)
Values('Sukhjeet','Singh','India','Asia')
go


Now only insert the values in First Name and Last Name columns. As we have created the Default Constraint on Country Name and Region, it should automatically insert CountryName='USA' and Region='North America'.

Insertinto dbo.Customer(FirstName,LastName)
Values ('John','Smith')
go

Insertinto dbo.Customer(FirstName,LastName)
Values ('Christy','Ladson')

Let's check the data in dbo.Customer table to make sure our Default Constraints are working as expected.

Select * from  dbo.Customer
How to create Default Constraint in SQL Server
When we created Default Constraints, we did not provide any name, let's check what names SQL Server has given them by using sys.objects

--Get the Constraint Names in SQL Server
Select * from sys.objects
where type_desc='DEFAULT_CONSTRAINT'

How to check Default Constraints information in SQL Server

If your company is using some naming standards and you would like to create the default constraint with those standards, you can specify the name while creating them. I am using to use DF_SchemaName_TableName_ColumnName for my constraint name as shown below.

use YourDatabaseName
Go
CreateTable dbo.tblCustomer
(
FirstName VARCHAR(50),
LastName VARCHAR(50),
CountryName VARCHAR(50) Constraint DF_dbo_tblCustomer_CountryName Default'USA' ,
Region VARCHAR(50) Constraint DF_dbo_tblCustomer_Region default'North America')

Let's run the query on sys.objects one more time to get Default Constraint name with Table name.

--Get the Constraint Names in SQL Server
Select name,object_name(Parent_object_id)
as TableName from sys.objects
where type_desc='DEFAULT_CONSTRAINT'

How to create Default Constraint with Name in SQL Server







How to add Default Constraint to existing Columns in SQL Server Table - SQL Server / TSQL Tutorial Part 91

$
0
0

Scenario:

You are working as SQL Server developer. You already has dbo.Customer table with First Name, Last Name, Country Name and Region Columns. The table contains some records as well. You need to provide Default Constraint scripts for Country Name='USA' and Region='North America'.

Solution:

Let's create dbo.Customer table with Default Constraints and insert some sample data first. 

use YourDatabaseName
Go
CreateTable dbo.Customer
(
FirstName VARCHAR(50),
LastName VARCHAR(50),
CountryName VARCHAR(50),
Region VARCHAR(50))

Go
--Insert some sample data
Insertinto dbo.Customer (FirstName,LastName,CountryName,Region)
Values('Aamir','Shahzad','Pakistan','Asia')
go
Insertinto dbo.Customer (FirstName,LastName,CountryName,Region)
Values('Sukhjeet','Singh','India','Asia')
go
Insertinto dbo.Customer(FirstName,LastName)
Values ('John','Smith')
go
Insertinto dbo.Customer(FirstName,LastName)
Values ('Christy','Ladson')
go

Let's check the data in dbo.Customer table.
How to add Default Constraint to existing SQL Server Table

Now let's alter the table and add Default Constraints by using below statements.

Altertable dbo.Customer
AddConstraint DF_dbo_Customer_CountryName Default'USA'for CountryName
,Constraint DF_dbo_Customer_Region default'North America'for Region

Let's insert couple of records without providing values for Country Name and Region Columns and see if Default Constraint working as expected.

Insertinto dbo.Customer(FirstName,LastName)
Values ('Chris','Cook')
go
Insertinto dbo.Customer(FirstName,LastName)
Values ('Lisa','L')

Let's check the data in dbo.Customer table again.
How to add Default Constraint to Existing Columns in SQL Server Table

As can be seen in above picture, the Default Constraint worked as expected.

How to List all Default Constraints with Columns in SQL Server Database - SQL Server / TSQL Tutorial Part 92

$
0
0

Scenario:

You are working as SQL Server developer, you need to write script that should return all the Default Constraints with Column Names, Table Names and Schema name from a SQL Server Database.


Solution:

We can use system objects such as views and tables to get all the Default Constraints, Column Name, Table Names and Schema name from SQL Server database.

In below query we are using three system views to get required information.

SELECT
DB_Name() AS DBName,
Schema_name(t.Schema_id)AS SchemaName,
t.name AS TableName,
c.name AS ColumnName,
d.name AS DefaultConstraintName,
d.definition AS DefaultDefinition
FROM sys.default_constraints d
INNERJOIN sys.columns c ON
d.parent_object_id = c.object_id
AND d.parent_column_id = c.column_id
INNERJOIN sys.tables t ON
t.object_id = c.object_id


I executed above script on my database and it returned below results.
How to get Default Constraint Names with Columns from SQL Server Database

How to create Tables Dynamically from Tab Delimited Files and Load data in SSIS Package - SSIS Tutorial

$
0
0

Scenario: Download Script

I wrote a post / video in which we learnt How to load flat files ( comma or pipe) delimited dynamically to SQL server Tables. Here is the link.

I received an email from one of the viewer and she was interested to load Tab Delimited files dynamically to SQL server Tables. The Package should be able to read the files from source folder, create the table after reading first row( header) and then load the data.

sample file
How to load Tab Delimited File dynamically to SQL Server Table

Solution:

The below package can be used to load comma, Pipe and Tab delimited. When need to use the Package for Tab delimited files, you have to set FileDelimiter variable value=TAB, if loading comma delimited files then provide comma.


We are going to use Script Task in this post to create table dynamically for each flat file and load it.

Step 1: Create New SSIS Package and Variables 
Open SSDT ( SQL Server Data Tools) and create new SSIS Package. After that go ahead and create variables so we can use them in configuration to pass values anytime our requirement change.

ArchiveFolder: Provide the folder path where you would like to move files after loading. Datetime part will be added to file name.
ColumnsDataType : Provide the data type you would like to use for newly created table/s.
SchemaName : Provide the schema name in which you would like to create your table/s.
FileDelimiter : Provide the delimiter which is used in your txt or csv files that can be , or | or TAB.
FileExtension : Provide the Extension of files you would like to load from folder.
LogFolder : Provide the folder path where you would like to create log file in case of error in script task
SourceFolder: Provide the source folder path where text files or csv files are places for import process.
How to load Tab delimited dynamically to SQL Server Tables in SSIS Package

Step 2:

Click in Connection Manager Pane and then Create ADO.NET Connection by providing Server Name and database Name. After creating I have renamed it to DBConn.

Create ADO.NET Connection so we can use in Script Task to load the data to Destination Tables 


Step 3: Add Variables to Script Task to use from SSIS Package
Bring the Script Task on Control Flow Pane in SSIS Package and open by double clicking Check-box in front of variable to add to Script Task.
Add variables to Script Task so we can load multiple Text files or csv files to SQL Server Tables in SSIS Package


Step 4: Add Script to Script task Editor in SSIS Package to create tables dynamically and load data from flat files
Click Edit Button and it will open Script Task Editor.
Under #region Namespaces, I have added below code

using System.IO;
using System.Data.SqlClient;


Under public void Main() { 
I have added below code.

string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
try
{

//Declare Variables
string SourceFolderPath = Dts.Variables["User::SourceFolder"].Value.ToString();
string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
string ArchiveFolder = Dts.Variables["User::ArchiveFolder"].Value.ToString();
string ColumnsDataType = Dts.Variables["User::ColumnsDataType"].Value.ToString();
string SchemaName = Dts.Variables["User::SchemaName"].Value.ToString();
//string ColumnList = "";
if (FileDelimiter == "TAB")
{
FileDelimiter = "\t";
}


//Reading file names one by one
string[] fileEntries = Directory.GetFiles(SourceFolderPath, "*" + FileExtension);
foreach (string fileName in fileEntries)
{

SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)
(Dts.Connections["DBConn"].AcquireConnection(Dts.Transaction) as SqlConnection);

//Writing Data of File Into Table
string TableName = "";
int counter = 0;
string line;
string ColumnList = "";
//MessageBox.Show(fileName);

System.IO.StreamReader SourceFile =
new System.IO.StreamReader(fileName);
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
ColumnList = "[" + line.Replace(FileDelimiter, "],[") + "]";
TableName = (((fileName.Replace(SourceFolderPath, "")).Replace(FileExtension, "")).Replace("\\", ""));
string CreateTableStatement = "
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[" + SchemaName + "].";
CreateTableStatement += "[" + TableName + "]'
)";
CreateTableStatement += "
AND type in (N'U'))DROP TABLE [" + SchemaName + "].";
CreateTableStatement += "
[" + TableName + "] Create Table " + SchemaName + ".[" + TableName + "]";
CreateTableStatement += "
([" + line.Replace(FileDelimiter, "] " + ColumnsDataType + ",[") + "] " + ColumnsDataType + ")";
SqlCommand CreateTableCmd = new SqlCommand(CreateTableStatement, myADONETConnection);
CreateTableCmd.ExecuteNonQuery();

// MessageBox.Show(CreateTableStatement);

}
else
{
string query = "
Insert into " + SchemaName + ".[" + TableName + "] (" + ColumnList + ") ";
query += "
VALUES('" + line.Replace(FileDelimiter, "','") + "')";

// MessageBox.Show(query.ToString());
SqlCommand myCommand1 = new SqlCommand(query, myADONETConnection);
myCommand1.ExecuteNonQuery();
}

counter++;
}

SourceFile.Close();
//move the file to archive folder after adding datetime to it
File.Move(fileName, ArchiveFolder + "
\\" + (fileName.Replace(SourceFolderPath, "")).Replace(FileExtension, "") + "_" + datetime + FileExtension);
Dts.TaskResult = (int)ScriptResults.Success;
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(Dts.Variables["
User::LogFolder"].Value.ToString()
+ "
\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
Dts.TaskResult = (int)ScriptResults.Failure;
}

}


 
I executed the package and it was able to able to create new table by reading header row from tab delimited file and load the data.

How to load Tab Delimited Files dynamically to SQL server Tables in SSIS Package


How to rename all Default Constraints according to Naming Standards or naming Convention in SQL Server - SQL Server / TSQL Tutorial Part 93

$
0
0

Scenario:

You are working as SQL Server developer, You need to prepare the scripts those can be used to rename Default Constraints as per your company's standards. Your company want to name the default constraints e.g 'DF_SchemaName_TableName_ColumnName'

Solution:

We can use sp_rename Stored Procedure to rename Default Constraints. To rename single Default Constraint we can use script like below

Exec sp_rename 'Current_Default_Constraint_Name','New Default Constraint Name'

as we need to run this script for all the default constraints, we can use below query to generate rename Default Constraints.

SELECT'exec sp_rename '''
+Schema_name(d.Schema_id)+'.'
+ '' + d.Name + ''''
+ ',''DF_' +Schema_Name(d.schema_id)
+'_'+t.name
+'_'+c.name+''''as RenameDefaultConstraintQuery
FROM sys.default_constraints d
INNERJOIN sys.columns c ON
d.parent_object_id = c.object_id
AND d.parent_column_id = c.column_id
INNERJOIN sys.tables t ON
t.object_id = c.object_id

I execute above query on one of the database and I got below results. If you want to exclude some tables you can always filter them in where clause.

How to rename all Default Constraints in SQL Server Database according to Naming Convention

How to drop all Default Constraints in SQL Server Database - SQL Server / TSQL Tutorial Part 94

$
0
0

Scenario:

You are working as SQL Server Developer, you need to generate scripts to drop all the Default Constraints in SQL Server Database.

Solution:

To drop Default Constraint, we use below syntax

Alter Table [SchemaName].[TableName]
Drop Constraint [Constraint Name]

Below query can be used to generate scripts to generate all Default Constraints in SQL Server Database.

USE YourDatabaseName
go
SELECT
DB_Name() AS DBName,
Schema_name(t.Schema_id)AS SchemaName,
t.name AS TableName,
c.name AS ColumnName,
d.name AS DefaultConstraintName,
d.definition AS DefaultDefinition,
'Alter table ['+Schema_name(t.Schema_id)+'].['
+t.name+'] Drop Constraint ['+d.name+']'as DropDefaultConstraintQuery
FROM sys.default_constraints d
INNERJOIN sys.columns c ON
d.parent_object_id = c.object_id
AND d.parent_column_id = c.column_id
INNERJOIN sys.tables t ON
t.object_id = c.object_id


If you want to exclude some tables or schema, you can further filter the records by using where clause in query. 
I executed above query and it generated drop scripts for all Default Constraints.
How to generate scripts to Drop all Default Constraints in SQL Server Database

Take the results from DropDefaultConstraint column and execute to drop Default Constraints.



How to generate Scripts to Add Default Constraints to Column in Multiple Tables in SQL Server Database - SQL Server / TSQL Tutorial Part 94

$
0
0

Scenario:

You are working as SQL Server Developer, your company has the database with tons of tables. Each Table has some audit columns such as CreatedOn, CreatedBy. No default Constraints were ever created on them. You want to create the Default Constraint on CreatedOn Column for all the table with value getdate(), also you want to create Default Constraint for CreatedBy=SUSER_SNAME().
You may have another column of type string and you would like to generate scripts for that too.

Solution:

The below script can be used to generate Default Constraint for given column in entire database for all the tables. The name for Default Constraint will be DF_SchemaName_TableName_ColumnName.

Let's generate Default Constraint scripts for CreatedOn column with value Getdate() by using below script.


Declare @ColumnName VARCHAR(128)
Declare @DefaultValue VARCHAR(100)
SET @ColumnName='CreatedON'
SET @DefaultValue='Getdate()'


Select Schema_Name(Schema_id) as SchemaName,
t.Name
as TableName,
C.Name
as ColumnName,
'Alter Table ['+Schema_Name(Schema_id)
+
'].['+t.Name+']'
+
' Add Constraint DF_'+Schema_Name(schema_id)
+
'_'+t.name
+
'_'+c.name+''
+
' default '+@DefaultValue+' for '
+ @ColumnName
as CreateDefaultConstraint
from sys.tables t
innerjoin sys.columns c
on t.object_id=c.object_id
and t.is_ms_shipped=0
and c.name=@ColumnName

Generate Scripts to Add Default Constraint to Column in Database in SQL Server
You only have to make change to @ColumnName and @DefaultValue variables as per your requirements. Let's use the same script to add Default Constraint to CreatedBy Column with value=SUSER_SNAME().

Declare @ColumnName VARCHAR(128)
Declare @DefaultValue VARCHAR(100)
SET @ColumnName='CreatedBy'
SET @DefaultValue='SUSER_SNAME()'


Select Schema_Name(Schema_id) as SchemaName,
t.Name
as TableName,
C.Name
as ColumnName,
'Alter Table ['+Schema_Name(Schema_id)
+
'].['+t.Name+']'
+
' Add Constraint DF_'+Schema_Name(schema_id)
+
'_'+t.name
+
'_'+c.name+''
+
' default '+@DefaultValue+' for '
+ @ColumnName
as CreateDefaultConstraint
from sys.tables t
innerjoin sys.columns c
on t.object_id=c.object_id
and t.is_ms_shipped=0
and c.name=@ColumnName
How to generate script to add  Default Constraint on column in SQL Server Database

Now let's consider that you want to set default value to some string value as we want to create Default Constraint for Region column='USA' , When set the value of @DefaultValue variable, add single quotes as shown below.

Declare @ColumnName VARCHAR(128)
Declare @DefaultValue VARCHAR(100)
SET @ColumnName='Region'
SET @DefaultValue='''USA'''


Select Schema_Name(Schema_id) as SchemaName,
t.Name
as TableName,
C.Name
as ColumnName,
'Alter Table ['+Schema_Name(Schema_id)
+
'].['+t.Name+']'
+
' Add Constraint DF_'+Schema_Name(schema_id)
+
'_'+t.name
+
'_'+c.name+''
+
' default '+@DefaultValue+' for '
+ @ColumnName
as CreateDefaultConstraint
from sys.tables t
innerjoin sys.columns c
on t.object_id=c.object_id
and t.is_ms_shipped=0
and c.name=@ColumnName

How to generate scripts to add Default Constraint on Column in multiple Tables in SQL Server Database



What is Unique Constraint in SQL Server - SQL Server / TSQL Tutorial Part 95

$
0
0

What is Unique Constraint in SQL Server:

Unique Constraint in SQL Server is created on a column or columns to restrict the column/s to accept only unique values.
Only single Null value is allowed in a column on which Unique Constraint is created.

Scenario:

Let's say that you are working as SQL Server developer for insurance company, you are asked to create dbo.Customer table that should have a column SSN and it should always accept Unique values.


Solution:

For the above scenario, we can use Unique Constraint on SSN Column. Below script can be used to create unique constraint on a column.

USE [YourDatabaseName]
GO
CREATETABLE [dbo].[Customer](
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[SSN] VARCHAR(11),
Unique(SSN)
)

--Insert sample records in table
Insertinto dbo.Customer(FirstName,LastName,SSN)
Values('Raza','M',Null)
,(
'Aamir','Shahzad','000-00-0001')
,(
'Aamir','Shahzad','000-00-0002')

Check the data in dbo.Customer table by using Select query
How to add Unique Constraint on a Column in SQL Server 

Let's use the system views to check if Unique Constraint is added and what name SQL Server has given to it.

SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'UNIQUE'

How to add Unique Constraint in SQL Server 

As we can see that the SQL Server has given "UQ__Customer__CA1E8E3C7E8AFCB1" name to Unique Constraint. If we want to implement some naming convention then we should had provided name by ourselves.

If we try to insert the value that already exists in Unique Constraint column, we will get below error.

Insertinto dbo.Customer(FirstName,LastName,SSN)
Values('Raza','M',Null)


Msg 2627, Level 14, State 1, Line 11
Violation of UNIQUE KEY constraint 'UQ__Customer__CA1E8E3C7E8AFCB1'. Cannot insert duplicate key in object 'dbo.Customer'. The duplicate key value is ().
The statement has been terminated.

If you would like to create the Unique Constraint with some naming convention, we can use below syntax.

USE [YourDatabaseName]
GO
CREATETABLE [dbo].[Customer](
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[SSN] VARCHAR(11),
Constraint UQ_Dbo_Customer_SSN Unique(SSN)
)





How to create Unique Constraint on Multiple Columns in SQL Server - SQL Server / TSQL Tutorial Part 96

$
0
0

Scenario:

You are working as SQL Server Developer, you are asked to provide create scripts for dbo.Customer table with Unique Constraint on First Name and Last Name columns.

Solution:

As we know that the Unique Constraint in SQL Server is created on a column or columns to restrict the column/s to accept only unique values.

The below script can be used to create Unique Constraint on multiple columns in our case FirstName and LastName.

USE [YourDatabaseName]
GO
CREATETABLE [dbo].[Customer](
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[SSN] VARCHAR(11),
Constraint UQ_Dbo_Customer_FName_LName Unique(FirstName,LastName)
)

--Let's insert some sample data to test Unique Constraint
Insertinto dbo.Customer(FirstName,LastName,SSN)
Values(Null,Null,'000-00-0000'),
(
'Aamir',Null,'000-00-0000'),
(
Null,'Aamir','000-00-0000')
,(
'Aamir','Shahzad','000-00-0001')
,(
'Raza','M','000-00-0002')

If you have noticed the insert statement, In First Record I have put both Null values for FirstName and Last Name. In 2nd record I used the value 'Aamir' for first name and Null for Last Name. In 3rd record vice versa of 2nd record. From here what we understand that the unique constraint is working on both column values. As long as the combined value from both columns is unique, it is going to let us insert even one of them is null.

If I would like to insert another record in which I have Null for last name, it will let me without any problem, as it is unique from existing values.

Insertinto dbo.Customer(FirstName,LastName,SSN)
Values('Raza',Null,'000-00-0000')

Let's check the records in table by using select query.
How to add Unique Constraint on Multiple Columns in SQL Server Table
If we try to insert a duplicate records, we will get below error.

Insertinto dbo.Customer(FirstName,LastName,SSN)
Values('Raza',Null,'000-00-0000')

Msg 2627, Level 14, State 1, Line 30
Violation of UNIQUE KEY constraint 'UQ_Dbo_Customer_FName_LName'. Cannot insert duplicate key in object 'dbo.Customer'. The duplicate key value is (Raza, ).
The statement has been terminated.

How to create Unique Constraint on Column for already existing Table - SQL Server / TSQL Tutorial Part 97

$
0
0

Scenario:

You are working as SQL Server developer, you need to create Unique Constraint on already existing table called dbo.Customer on column SSN.

Solution:

Let's create the dbo.Customer table first by using below script.

USE [YourDatabaseName]
GO
CREATETABLE [dbo].[Customer](
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[SSN] VARCHAR(11)
)

Create Unique Constraint on SSN Column by using below script.

AlterTable dbo.Customer
AddConstraint UQ_dbo_Customer_SSN Unique(SSN)

If you need to create Unique Constraint on multiple columns, you can use below syntax. I am creating Unique Constraint for FirstName and LastName.

AlterTable dbo.Customer
AddConstraint UQ_dbo_Customer_FName_LName Unique(FirstName,LastName)

Use below query to check if Unique Constraints are created successfully.

SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'UNIQUE'

How to create Unique Constraint on Column for existing SQL Server Table



How to get list of columns with Unique Constraints in SQL Server Database - SQL Server / TSQL Tutorial Part 98

$
0
0

Scenario: 

You are working as SQL Server developer, you are asked to provide a query that should return all the Unique Constraint with Columns, Table and Schema Name.

Solution:

We can use system objects to get list of unique constraints with columns, tables and schema name. Below query will return you all the unique constraints with columns from SQL Server database.


;WITH CTE_UQ
AS (
SELECT t.Table_Schema AS TableSchema
,t.table_name AS TableName
,c.column_name AS ColumnName
,t.constraint_name AS UniqueConstraintName
,t.constraint_type AS ConstraintType
FROM information_schema.table_constraints t
LEFTJOIN information_schema.key_column_usage c
ON t.constraint_catalog = c.constraint_catalog
AND t.constraint_schema = c.constraint_schema
AND t.constraint_name = c.constraint_name
WHERE t.constraint_type = 'UNIQUE'
)
SELECT TableSchema
,TableName
,UniqueConstraintName
,ConstraintType
,stuff((
SELECT',' + ColumnName
FROM CTE_UQ i
WHERE i.TableSchema = o.TableSchema
AND i.TableName = o.TableName
AND i.UniqueConstraintName = o.UniqueConstraintName
FOR XML path('')
), 1, 1, '') UniqueColumnList
FROM CTE_UQ o
GROUPBY TableSchema
,TableName
,UniqueConstraintName
,ConstraintType

I executed above query on database and got below results.
How to get Column List with Unique Constraints in SQL Server Database

Viewing all 1874 articles
Browse latest View live