DotNetWorld logo

SQL

Splitting a Field
Adding a Composite Primary Key
Adding a Foreign Key

Using Replace in an Update

Update Author Set City = Replace(city,'salt','Olympic')
Changes city field from salt lake city to Olympic lake city

Trimming Leading Spaces

Update tablename
set FieldName = trim(fieldname)

Reseed identities in sql server

dbcc checkident(mytable,reseed,0)

Loading a CSV file into SQL server

BULK INSERT MyTable
From 'c:\mydirectory\mysubdirectory\myfile.csv#
WITH
(FieldTerminator = ',';
RowTerminator = '\n'
)

Checking to see if an SP exists

If Exists(Select * from sysobjects where id = object_id('storedprocedurename') and objectproperty(id,'IsProcedure')=1)

Using a Cursor

Declare @AssetComposers_Cursor Cursor
set @AssetComposers_cursor = CURSOR READ_ONLY
FOR
Select AssetComposerId
From Vad_AssetComposers
Where ComposerId = @OriginalComposerId
Open "AssetComposers_Cursor
FETCH NEXT FROM @AssetComposers_Cursor
INTO @AssetComposerId
END
CLOSE @AssetComposers_Cursor
DEALLOCATE @AssetComposers_Cursor

Adding to a Date

DateAdd(Year,n,GetDate())

Contains

SELECT PRODUCTNAME
FROM *PRODUCTS
WHERE CONTAINS (ProductName,'apples')
returns all products that contain the word apple
*must be full-text indexed

Creating a table from another table

SELECT * INTO TableA FROM TableB

Insert Trigger

CREATE TRIGGER trig_addAuthor
ON authors
FOR INSERT
AS
-- Get the first and last name of new author
DECLARE @newName VARCHAR(100)
SELECT @newName = (SELECT au_fName + ' ' + au_lName FROM Inserted)
-- Print the name of the new author
PRINT 'New author "' + @newName + '" added.

Splitting a Field


e.g. name = "Robert*James*Smith"

put the names in fields
FNAME, MNAME, LNAME
Update MyTable
FNAME = Substring(Name,1,CharIndex('*',Name) - 1,
MName=Substring(Name,CharIndex('*',Name) + 1

Adding a Composite Primary Key


Alter Table tableName add primary key (column1,column2)

Adding a Foreign Key


Alter table product_belongs_to_product

Add Constraint fk_ProductreferecnceProduct foreign key (KitId)

Also

ALTER TABLE ORDERS
ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);