Skip to main content

Posts

Showing posts from 2013

Constraints in sql server

Constraints   - Constraints are the rules enforced on data columns on table. This ensures the accuracy and reliability of the data in the database. Constraints define some conditions that restricts the column to remain true while inserting or updating or deleting data in column. Constraints can be defined in two ways   1) The constraints can be specified immediately after the column definition. This is called column-level definition.   2) The constraints can be specified after all the columns are defined. This is called table-level definition.   Types of Constraints in SQL-Server NOT NULL - This constraint is responsible for a column to confirm that a column cannot have a null value. DEFAULT – This constraint provides a default value when specified non for this column. UNIQUE - This constraint insure that each row for the column has different value. PRIMARY KEY - Primary key constraint is a combination of a NOT NULL constraint and a UNIQUE constra

CHECK constraint in sql server

CHECK- The CHECK responsible to enables a condition to check the value being entered into a record Example- In following example we create PRODUCT table it has PRICE column and its value should be greater than 20.00, so that you cannot have any product which price is less than or equal to 20.00 CREATE TABLE PRODUCT ( ID INT NOT NULL IDENTITY ( 1 , 1 ), SKU VARCHAR ( 20 ) NOT NULL, TITLE VARCHAR ( 200 ) NOT NULL, PRICE MONEY NOT NULL CHECK ( PRICE > 20.00 ), DISCRIPTION VARCHAR ( 2000 )   NULL, DTCREATE DATETIME NULL CONSTRAINT pk_ID PRIMARY KEY ( ID ) ) If table already exists then use following query to create check constraints. ALTER TABLE PRODUCT ADD CHECK ( PRICE > 20.00 )

FOREIGN KEY constraint in sql server

FOREIGN KEY- This constraints responsible to uniquely identified a rows or records to another table. Example- Following table structure can clear your concept of foreign key constraint. Product Table CREATE TABLE PRODUCT ( ID INT NOT NULL IDENTITY ( 1 , 1 ), SKU VARCHAR ( 20 ) NOT NULL, TITLE VARCHAR ( 200 ) NOT NULL, PRICE MONEY NOT NULL, DISCRIPTION VARCHAR ( 2000 )   NULL, DTCREATE DATETIME NULL CONSTRAINT pk_ID PRIMARY KEY ( ID ) ) Product Order Table CREATE TABLE PRODUCT_IMAGE ( ID INT NOT NULL IDENTITY ( 1 , 1 ), PRODUCT_ID INT NOT NULL  REFERENCES  PRODUCT ( ID ) , IMGURL VARCHAR ( 200 ) NOT NULL , DTCREATE DATETIME ) To create foreign key constraint to existing table use following query. ALTER TABLE PRODUCT_IMAGE  ADD FOREIGN KEY ( PRODUCT_ID )  REFERENCES PRODUCT ( ID )

PRIMARY KEY constraint in sql server

PRIMARY KEY- Primary key constraint is a combination of a NOT NULL constraint and a UNIQUE constraint. This constraint ensures that the specific column for a table have an unique identity. Example- Following we create a table PRODUCT in which column ID has primary key constraints. CREATE TABLE PRODUCT ( ID INT NOT NULL IDENTITY ( 1 , 1 ), SKU VARCHAR ( 20 ) NOT NULL, TITLE VARCHAR ( 200 ) NOT NULL, PRICE MONEY NOT NULL, DISCRIPTION VARCHAR ( 2000 )   NULL, DTCREATE DATETIME NULL CONSTRAINT pk_ID PRIMARY KEY ( ID ) ) If table already exits then use following query. ALTER TABLE PRODUCT  ADD CONSTRAINT pk_products_pid PRIMARY KEY ( ID )

UNIQUE KEY constraint in sql server

UNIQUE- This constraint insure that each row for the column has different value. Example- Following create a table PRODUCT, column SKU has unique key constraints. CREATE TABLE PRODUCT ( ID INT NOT NULL, SKU VARCHAR ( 20 ) NOT NULL UNIQUE , TITLE VARCHAR ( 200 ) NOT NULL, PRICE MONEY NOT NULL, DISCRIPTION VARCHAR ( 2000 )   NULL, DTCREATE DATETIME NULL ) If table has already been created and we want to apply unique constraints then use following query. ALTER TABLE PRODUCT ADD UNIQUE ( SKU ) You can also use following syntax, which supports naming the constraint in multiple columns as well ALTER TABLE PRODUCT ADD UNIQUE ( SKU,ID )

DEFAULT constraint in sql server

DEFAULT – This constraint provides a default value when specified non for this column. Example- Following create a table PRODUCT, column DTCREATE has default value GETDATE() it will store system’s date-time by default if value is not specified for this column. CREATE TABLE PRODUCT ( ID INT NOT NULL, SKU VARCHAR ( 20 ) NOT NULL, TITLE VARCHAR ( 200 ) NOT NULL, PRICE MONEY NOT NULL, DISCRIPTION VARCHAR ( 2000 )   NULL, DTCREATE DATETIME DEFAULT GETDATE () ) If PRODUCT table has already been created and you want apply default price in PRICE column use following query (for SQL server). ALTER TABLE PRODUCT ADD CONSTRAINT DF_SomePrice DEFAULT 20.00 FOR PRICE

NOT NULL constraint in sql server

NOT NULL- This constraint is responsible for a column to confirm that a column cannot have a null value. Example- Following we create new table PRODUCT and add six columns where ID, SKU, TITLE, PRICE specify not to accept NULLs. CREATE TABLE PRODUCT ( ID INT NOT NULL, SKU VARCHAR ( 20 ) NOT NULL, TITLE VARCHAR ( 200 ) NOT NULL, PRICE MONEY NOT NULL, DISCRIPTION VARCHAR ( 2000 )   NULL, DTCREATE DATETIME NULL ) If PRODUCT table already created, then to add a NOT NULL constraints to SKU column we use following query.   ALTER TABLE PRODUCT   ALTER COLUMN SKU  VARCHAR ( 20 ) NOT NULL

Inner join in sql server

INNER JOIN Inner join responsible to returns rows which have a match in both tables. See following example:- CREATE TABLE #ORDER ( orderId INT IDENTITY ( 1 , 1 ), fName VARCHAR ( 400 ), lName VARCHAR ( 400 ), ShipAddress VARCHAR ( 1000 ), dtCreate DATETIME ) CREATE TABLE #ORDER_DETAILS ( orderDetailsId INT IDENTITY ( 1 , 1 ), productName VARCHAR ( 400 ), pPrice DECIMAL ( 18 , 2 ), iQTY INT , orderId INT , dtCreate DATETIME ) INSERT INTO #ORDER ( fName , lName , ShipAddress , dtCreate ) SELECT 'Dilip' , 'SINGH' , 'New Delhi' , GETDATE () UNION ALL SELECT 'Nirmit' , 'katiyar' , 'Mumbai' , GETDATE () UNION ALL SELECT 'Raj' , 'Dongra' , 'Jharkhand' , GETDATE () UNION ALL SELECT 'Salim' , 'safi' , 'Muradnagar UP' , GETDATE () INSERT INTO #ORDER_DETAILS ( productName , pPrice , iQTY , orderId , dtCreate ) SELE

difference between @@IDENTITY, SELECT SCOPE_IDENTITY(),SELECT IDENT_CURRENT

SELECT @@IDENTITY: it’s responsible to   returns the last identity value generated for any table in the current session, across all scopes (i.e. global scope). SELECT SCOPE_IDENTITY():   It’s responsible to   returns the last identity value generated for any table in the current session and the current scope(i.e. local scope). SELECT IDENT_CURRENT(‘table_name’): It’s responsible to   returns the last identity value generated for a specific table in any session and any scope (i.e. global scope). Following example may clear your concept. CREATE TABLE TBL1 ( id INT IDENTITY ( 1 , 1 )) CREATE TABLE TBL2 ( id INT IDENTITY ( 100 , 1 )) GO CREATE TRIGGER TGR ON TBL1 FOR INSERT AS BEGIN INSERT TBL2 DEFAULT VALUES END GO INSERT TBL1 DEFAULT VALUES SELECT @@IDENTITY AS FOR_IDENTITY SELECT SCOPE_IDENTITY () AS FOR_SCOPR_IDENDITY SELECT IDENT_CURRENT ( 'TBL1' ) AS FOR_IDENT_CURRENT_TBL1 SELECT IDENT_CURRENT ( 'TBL2'

difference between Primary key and Unique Key

Primary key Unique Key 1-       Primary key doesn’t have null value. 2-       A table can have only one primary key. 3-       By default primary key have clustered index. Unique key can hold null value but only once. A table can have more than on unique key. By default Unique key have non- clustered index.

Delete or Cleanup Backup History in sql server.

All backup history is stored in msdb database. Following stored procedure can be execute with parameter, here we clean history before 30 days.     USE   msdb GO DECLARE   @BeforeDays   DATETIME SET   @BeforeDays   =   CONVERT ( VARCHAR ( 10 ),   DATEADD ( dd , - 30 , GETDATE ()),   101 ) EXEC   sp_delete_backuphistory   @BeforeDays GO

remove special characters from string in sql server

Using This Query you can remove special characters from string in sql DECLARE @str VARCHAR ( 400 )     DECLARE @expres  VARCHAR ( 50 ) = '%[~,@,#,$,%,&,*,(,),.,!]%'       SET @str = '(remove) ~special~ *characters. from string in sql!'       WHILE PATINDEX ( @expres , @str ) > 0           SET @str = Replace ( REPLACE ( @str , SUBSTRING ( @str , PATINDEX ( @expres , @str ), 1 ), '' ), '-' , ' ' )       SELECT @str

Add minute, hour, day, month in date in sql server

By using DATEADD(<interval>,<increment int>,<expression smalldatetime>) function we can add or reduce hour, day etc.. For increment or decrement from the datetime the query are given below. For add minute DATEADD(MINUTE,20,GETDATE()) For reduce minute DATEADD(MINUTE,-20,GETDATE()) For add hour DATEADD(HOUR,20,GETDATE()) For reduce hour DATEADD(HOUR,-20,GETDATE()) For add day DATEADD(DAY,20,GETDATE()) For reduce day DATEADD(DAY,-20,GETDATE()) For add month   DATEADD(MONTH,20,GETDATE()) For reduce month DATEADD(MONTH,-20,GETDATE()) For add year   DATEADD(YEAR,20,GETDATE()) For reduce year  DATEADD(YEAR,-20,GETDATE())

TRY/CATCH and error handling in SQL server 2005/2008

SQL Server 2005 provide a strong set of tool to handle error or exception, in privious version it was not easy to handle exceptions. We use TRY/CATCH in SQL Server same as populer languages, We write saperate logic and exception handling code. Syntax: BEGIN TRY -- Your Code or query END TRY BEGIN CATCH -- Handling code END CATCH We write our logic code within TRy bolck and exception code in CATCh block, if nay error occur in logic code it jumps to CATCH  block, resume the execution and transaction is rollback. Functions which is use in CATCH 1- ERROR_NUMBER() Returns error no othe error message. 2- ERROR_SEVERITY() returns the error severity regardless of how many times it is run. 3- ERROR_STATE() Returns the state number of error messages that cause the catch block. 4- ERROR_PROCEDURE() Return the Procedure Name. 5- ERROR_LINE() Return error line number. 6- ERROR_MESSAGE() return error description. Note : If we are calling all above method out side from C