SQL Server Tips

Unicode - Stored Procedures - newid() - Constraints - Case Sensitive search - Backup - Enumerate databases


Use N'some text' to mark "some text" as a unicode text in SQL statements. Useful for Cyrillic, for example.


Stored Procedures

Check whether a stored procedure exists, create it, execute it.

-- Create Stored Procedure
USE ClassNorthwind
GO

IF EXISTS (SELECT * FROM dbo.sysobjects
		WHERE id = object_id(N'[dbo].[MyOrders]')
		AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
	DROP PROCEDURE [dbo].[MyOrders]
GO

CREATE PROCEDURE MyOrders
	AS
	SELECT * FROM Orders
	WHERE RequiredDate < GETDATE() AND ShippedDate IS NULL
GO

-- Execute Stored Procedure by Itself
EXEC MyOrders
GO

newid() function is used as a default value to create a GUID (unique) value upon Insert of a row.


Constraints

Here is an SQL script that deletes the rows from a table. It disables the constraints before deleting and restores them afterwards.

SET NOCOUNT ON;

-- set constraints off.
ALTER TABLE [Tcountry] NOCHECK CONSTRAINT ALL;

delete from Tcountry;

-- set constraints on.
ALTER TABLE [Tcountry] CHECK CONSTRAINT ALL;

Case Sensitive search

Database collation determines whether the string comparison is case-sensitive or case-insensitive.


Backup

use master
backup database database_name to disk = 'c:\temp\file.dat'

Restore

use master
go

restore database alice from disk = 'c:\temp\file.dat' with replace
go

Case 2:

Backup and Restore SQL Server Databases to Disk

Backup and Restore commands can only be executed from within the master database; this is accomplished by issuing the USE master command. The example below backs up the USRDB database to disk.

USE master
BACKUP DATABASE USRDB TO DISK = 'C:\Backup\Renee\DatabaseBackup\2005.07.20.1200.USRDB.Bak'

Restoring the database is almost no different than backing it up. The only additional to-do is to drop the database before you restore it. The example below restores the backup that was created from the above command.

USE master
DROP DATABASE USRDB
RESTORE DATABASE USRDB FROM DISK = 'C:\Backup\Renee\DatabaseBackup\2005.07.20.1200.USRDB.Bak'


Enumerate Databases at server

sp_databases


Clear Query Cache

To clear the cache after running a query execute the code below. Otherwise, the query cache is cleared only on server restart.

CHECKPOINT

DBCC DROPCLEANBUFFERS