Professional Documents
Culture Documents
SQL Server Ato Z
SQL Server Ato Z
SQL Server Ato Z
USE master
GO
EXEC sp_dboption myOldData, 'Single User', True
EXEC sp_renamedb 'myOldData', 'myNewData'
EXEC sp_dboption myNewData, 'Single User', False
GO
4. Working With Tables
Traditionally known as CRUD - Create, Read, Update, and Delete
1. Creating a Table
1. syntax:
2. "SELECT INTO"
Tables can also be created with the "SELECT INTO" construct SELECT select_list INTO
new_table_name FROM table_list WHERE search_condition Note: if new_table_name starts with #, it will
be put in the temp tables ##, it will be in temp tables and be global (accessable to all other sessions)
Example using Temp tables:
SELECT * INTO #tempcustomers2 FROM customers
SELECT * FROM #tempcustomers2
Temp tables go away when the server is restarted or at the end of the connection.
3. Deleting a table: DROP TABLE table_name
4. Add a column: ALTER TABLE SDSurveys ADD KQLogic VARCHAR (1000) NULLAdd a column with check for
existence first
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MyTableName' AND COLUMN_NAME = 'newcolumn')
BEGIN
ALTER TABLE MyTableName ADD newcolumn varchar(32) NOT NULL DEFAULT ''
END
5. Remove a column: ALTER TABLE SDSurveys drop column KQLogic
6. Show list of columns in a table sp_columns table_name
5. Working With Rows
1. Inserting Rows into a Table
1. Syntax:
INSERT INTO table_name [(column_id1,column_id2...)]
VALUES (value1,value2,...)
examples:
INSERT INTO autos (1996,'ford') -- INTO is an optional keyword in SQLServer
INSERT tablename VALUES ('a','b',DEFAULT,i) -- DEFAULT is a key word
INSERT INTO title VALUES(1001,'The Odyssey','Homer',NULL)
2. add multiple rows to a table
INSERT INTO table (c17,c4,c8,c3) SELECT a,b,c,d FROM ...
2. Examples:
update users set password = 'newpass' WHERE user = 'quest'
update users set password = 'newpass' WHERE (UserID > 1) AND (UserID < 113)
update users set password = 'newpass', change='Y' WHERE user = 'quest'
UPDATE discounts SET discount = discount + .1 WHERE lowqty >= 100
UPDATE employees SET LNAME = UPPER(LNAME)
3. Deleting rows from a Table DELETE FROM table_name [WHERE search_condition] example:
DELETE FROM mytable WHERE userid < 50
DELETE tablename -- deletes all rows in a table (see "DROP TABLE" to delete a table)
TRUNCATE TABLE tablename -- deletes all rows, but doesn't log transaction
DELETE titles WHERE title_id in (SELECT title_id FROM ...)
4. Example of CAST, Datepart, and STR
In the example below, "dtime" is a column containing the datetime. "datepart(yy,dtime)" produces the year,
"str(datepart(dy,dtime),3)" produces a right justified day-of-the-year.
SELECT cast(datepart(yy,dtime) as varchar(4)) + ' ' + str(datepart(dy,dtime),3) as
'Year Day',
COUNT(time) AS 'Key Question Pages',
avg(time) AS 'avg time (msec)'
FROM sdrespondentpagetimes
WHERE name='Key'
group by cast(datepart(yy,dtime) as varchar(4)) + ' ' + str(datepart(dy,dtime),3)
order by cast(datepart(yy,dtime) as varchar(4)) + ' ' + str(datepart(dy,dtime),3) asc
The results:
Year Day Key Question Pages avg time (msec)
--------- ------------------ ---------------
2004 51 13 768
2004 54 10 747
2004 56 6 1090
2004 57 34 702
...
2004 351 1 6000
2004 362 14 548
2005 4 3 629
2005 5 20 834
2005 7 10 469
2005 10 1 3593
2005 11 1228 269
Top rated books on SQL Server development:
6. SQL Server Utilities
1. osql - the command line batch interface to SQL Server
1. To EXECUTE a single statement use the -Q option
osql -Umoi -P"mypassword"
-Q"INSERT DATA_TABLE (column1, column2) values col1_value,
col2_value"
2. To have osql run a script file, (e.g., testSQL.SQL), use the -i option
osql -Umyuserid -P"mypassword" -itestSQL.SQL
3. Then to get things back out use the -o option:
osql -Umoi -P
-Q"SELECT column1, column2 FROM DATA_TABLE" -oOutput_file
4. To specify a host: -H delphi
5. To specify a server: -S delphi
6. To specify a server running SQLExpress: -S "delphi\SqlExpress"
7. to specify a database: -d db3
8. to surpress the headers: -h-1
9. to specify a separator: -s!
10. to set the line width to 5000: -w5000
A better way to handle the password is to set an environmental variable, "OSQLPASSWORD", so the "-U"
option may be omitted.
2. To get a list of all databases on a server
SELECT DISTINCT name FROM SYSDATABASES
3. To see which service pack (if any is installed)
SELECT SERVERPROPERTY('ProductLevel')
Returns:
'RTM' = shipping version.
'SPn' = service pack version
'Bn', = beta version.
4. To impersonate a user:
SETUSER 'mynewname'
GO
(SQL statements)
3. Aliasing tables
SELECT a.title_id, a.au_id, b.au_id
FROM titleauthor a
INNER JOIN titleauthor b
ON a.title_id = b.title_id
WHERE a.au_id < b.au_id
4. how to preface info in a column with a string, 'x-',
UPDATE mytable SET mycolumn = 'x-'+mycolumn
5. wildcards:
Wildcard Meaning
% Any string of zero or more characters
_ Any single character
[] Any single character within the specified range ([a-f]) or set
([abcdef])
[^] Any single character not within the specified range ([^a-f]) or set ([^abcdef])
LIKE 'Mc%' searches for all names that begin with the letters "Mc" (McBadden).
SELECT column_name FROM table WHERE mystring LIKE '%[XYZ]'
8. Stored Procedures
1. Stored Procedures
1. General syntax of stored procedure
CREATE PROCEDURE pname
@var vartype[=defaultvalue][,@var2 vartype]
AS
...
GO
2. Declaring Variables
DECLARE @varname type[,@varname type]* -- to define a variable
DECLARE @x int
SELECT @x = 5
3. Simple Example
CREATE PROCEDURE emplist
AS
SELECT empname, title, salary
FROM emp
ORDER BY title
GO
IF @middleinitial = NULL OR
@street = NULL OR
@city = NULL OR
@state = NULL OR
@zip = NULL OR
@phone_no = NULL
BEGIN
PRINT " "
PRINT " Please reenter this Adult Member."
PRINT " You must provide Last name, First name, Middle initial, "
PRINT " Street, City, State, Zip, and Phone number."
PRINT " "
RETURN
END
BEGIN TRANSACTION
INSERT member
( member_no, lastname, firstname, middleinitial, photograph)
VALUES
(@member_no, @lastname, @firstname, @middleinitial, NULL )
IF @@error <> 0
BEGIN
ROLLBACK TRAN
RETURN
END
INSERT adult
( member_no, street, city, state, zip, phone_no, expr_date)
VALUES
(@member_no, @street, @city, @state, @zip, @phone_no,
dateadd(year,1,getdate()) )
IF @@error != 0
BEGIN
ROLLBACK TRAN
RETURN
END
COMMIT TRANSACTION
GO
8. Another Example
CREATE PROCEDURE overdue_books
AS
SELECT member.lastname,copy_no,due_date FROM loan
JOIN member ON loan.member_no = member.member_no
WHERE DATEDIFF(DAY,GETDATE(),due_date)>1
GO
9. OUTPUT parameter
Example using the OUTPUT parameter
** This script file creates a procedure, LOANCOUNT,
** that returns a status of 0 if a member has any
** loans. If a member has no loans, it returns a
** status of -1.
USE library
GO CREATE PROC loancount @member_no member_no, @loancount int OUTPUT AS IF
EXISTS (SELECT
* FROM loan WHERE member_no = @member_no)
BEGIN SELECT
@loancount=COUNT(*) FROM loan WHERE member_no = @member_no RETURN
(0) END ELSE RETURN (-1)
GO
--NOTE: if any syntax errors in a batch, nothing in batch runs
-- all the statements are rolled together for syntax checking
-- if any statements have problems the "GO" is not executed.
9. Control of Flow
1. Control of Flow
1. IF
IF(condition)
BEGIN
...
END
ELSE
BEGIN
...
END
Example:
IF (SELECT COUNT(member_no)
FROM loan
WHERE member_no = @param) <= 4
RETURN 1
ELSE
RETURN 2
GO
2. WHILE
1. Syntax
WHILE condition BEGIN ... END BREAK/CONTINUE
2. Example of simple WHILE statement
set nocount on
declare @i int SELECT @i = 0
while (@i < 10)
BEGIN
SELECT 'i = ' + convert(char(5),@i)
SELECT @i = @i + 1
END
set nocount off
Code to insert 3000 rows into the database
DECLARE @i INT
SET @i=10000
WHILE(@i <= 30000)
BEGIN
INSERT INTO mytable (date, thread, level, logger, server, userid, message)
VALUES
(GETDATE(),'0000','INFO','XYZ1','LogFile',@i,'my message')
SET @i=@i+1
END
3. Example to show space used by each table
DECLARE @next VARCHAR(30)
SELECT @next = ' ' --Makes it "not null"
WHILE @next IS NOT NULL
BEGIN
SELECT @next = MIN(name)
FROM sysobjects
WHERE type = 'U' --User Tables
AND name > @next
ORDER BY name
EXECUTE sp_spaceused @next
END
4. RETURN used for 1 non-null integer
CREATE PROCEDURE checkmem
@param INT
AS
IF (SELECT COUNT(member_no)
FROM loan
WHERE member_no = @param) <= 4
RETURN 1
ELSE
RETURN 2
GO
To use this construct:
DECLARE @ret INT
EXECUTE @ret = checkmem 100
2. Misc commands
1. Example to create many databases
set nocount on
declare @i int SELECT @i = 2
declare @si char(1)
while (@i < 5)
BEGIN
SELECT @si = convert(char(1),@i)
SELECT 'i = ' + convert(char(5),@i)
exec('CREATE DATABASE db'+@si+' ON sndat = 1 LOG ON snlog = 1')
SELECT @i = @i + 1
END
set nocount off
2. sp_tables
sp_tables -- to show a list of tables in a database:
-- or
SELECT name FROM sysobjects WHERE type = 'u'
3. Change the size of varchar column
You may need to add the 'NOT NULL' option if your column is an indexed column
ALTER TABLE MyTableName ALTER COLUMN MyColumnName varchar(32)
4. Working with parameterized SQL
You have to declare and set the variable
declare @id int
select @id = 4140
SELECT userid FROM mytable WHERE userid > @id ORDER BY userid
5. loop thru all the tables in a database and UPDATE their Statistics
set nocount on
declare @next varchar(30)
SELECT @next = ' '
while @next IS NOT NULL
BEGIN
SELECT @next = MIN(name) FROM sysobjects WHERE type = 'u' and name > @next
SELECT 'next is ' + @next
IF @next IS NOT null
BEGIN
EXECUTE ('UPDATE STATISTICS ' + @next)
END
END
set nocount on
6. loop thru all the databases and print the name. (Useful for performing operations on each database).
set nocount on
use master
declare @next varchar(30)
SELECT @next = ' '
while @next IS NOT NULL
BEGIN
SELECT @next = MIN(name) FROM sysdatabases WHERE dbid > 5 AND name > @next
--SELECT 'next is ' + @next
IF @next IS NOT null
BEGIN
SELECT 'Looking at database',@next
END
END
set nocount on
7. RAISERROR This writes a message to the event log
RAISERROR('** this is my message',16,1) WITH LOG
RAISERROR('** this is my message',servity,state) WITH LOG
- GROUP BY
- COMPUTE or COMPUTE BY
- WITH CUBE or WITH ROLLUP
2. Example of COMPUTE
SELECT respondents.surveyName,
min(minValue) as 'desired min age',
min(a1) as 'actual min age',
abs(min(minValue) - min(a1)) as 'diff min age',
max(maxValue) as 'desired max age',
max(a1) as 'actual max age',
abs(max(maxValue) - max(a1)) as 'diff max age',
(min(minValue)+max(maxValue))/2 as 'desired avg age' ,
avg(a1) as 'actual avg age',
abs((min(minValue)+max(maxValue))/2 - avg(a1)) as 'diff avg age',
abs(min(minValue) - min(a1))+abs(max(maxValue) - max(a1))+ abs((min(minValue) +
max(maxValue))/2 - avg(a1)) as 'Total Skew'
from respondents join surveyDirectorQuotas on surveyDirectorQuotas.surveyName =
respondents.surveyName
--where respondents.surveyName = 'EClientE2'
and quotaQuestion = '_age'
group by respondents.surveyName
COMPUTE count(respondents.surveyName),
sum(abs(min(minValue) - min(a1))+abs(max(maxValue) - max(a1))+
abs((min(minValue)+max(maxValue))/2 - avg(a1)))
3. NULLIF (expr1,epr2) returns null if the two expressions are equal
SELECT AVG(NULLIF(royaltyper, 100))
AS 'Average Shared Royalty %'
FROM titleauthor
4. COLESCE(expr1,expr2,...exprN) -- returns first non-null value
5. ISNULL
Wonderful function that returns a specified value (in this example -1) if the query returns null.
SELECT ISNULL( (SELECT userid FROM billing WHERE pid = @pid) ,-1)
6. Misc
/* What database is now open? */
SELECT "Open Database is:",DB_NAME()
/* What is it's unique database identifier? */
SELECT "Database ID is:",DB_ID()
/* What is the current host machine name? */
SELECT "Host Name is:",HOST_NAME()
/* What is the login name of the current user? */
SELECT "Login Name is:", SUSER_NAME()
/* What is the database user name of the current user? */
SELECT "DB User Name is:",USER_NAME()
7. ARITHMETIC OPERATORS
SELECT price,
(price * 1.1) AS 'New Price',
title
FROM titles
--Round to 2 decimals
SELECT price,
CONVERT(MONEY, (price * 1.1)) AS 'New Price',
title
FROM titles
8. MATHEMATICAL FUNCTIONS
ABS (numeric_expr) Absolute value of the numeric
CEILING (numeric_expr) Smallest integer greater than or equal to
the numeric expression.
COS (float_expr) Trigonometric cosine of the specified angle (in radians)
RAND ([seed]) Random approximate numeric (float) value between 0 and 1,
ROUND (numeric_expr, length) Numeric expression rounded off to the
length (or precision)
Example:
SELECT price,
FLOOR(price) AS 'Floor Price',
CEILING(price) AS 'Ceiling Price'
FROM titles
• TRANSACTIONS
BEGIN TRANSACTION -- forces all or none of the following commands
INSERT ...
INSERT ...
IF()
ROLLBACK TRANSACTION
COMMIT TRANSACTION
• Using @@error
IF @@error <> 0 BEGIN ROLLBACK TRAN
RETURN END
• LOCKS
SELECT * FROM authors (nolock) -- will read even locked pages
Examples:
SELECT 'The price for ' +
CONVERT(char(38), title) -- doing a substring but appends spaces to make it 38
+ ' is $' + CONVERT(varchar(10), price) FROM titles
--Round to 2 decimals
SELECT price,
CONVERT(MONEY, (price * 1.1)) AS 'New Price',
title
FROM titles
• ORDER BY
ORDER BY sorts results sets
1. example:
SELECT column_name, COUNT(column_name) as mycount
FROM table_name ORDER BY mycount [ASC | DESC]
2. ORDER BY can have mulitple arguments
SELECT colA,colB,colC FROM table1 ORDER BY colB, colC
and you can add in the direction of the sort
SELECT colA,colB,colC FROM table1 ORDER BY colB ASC, colC DESC
3. ORDER BY will also take a number specifying which columns to sort by. In this case the second and
third, so it would be colB and colC.
SELECT colA,colB,colC FROM table1 ORDER BY 2, 3
4. example:
SELECT member_no,loan=count(member_no)
FROM loanhist
GROUP BY member_no
HAVING count(member_no) > 50
member_no loan
--------- -----------
2 442
3 130
4 104
5 260
6 78
5. Another Example
SELECT member_no,
date=loanhist.out_date,
fine=loanhist.fine_assessed,
paid=loanhist.fine_paid
FROM loanhist
WHERE (member_no BETWEEN 100 AND 150) AND (fine_assessed -
ISNULL(fine_paid,0) > 0)
ORDER BY member_no
COMPUTE sum(fine_paid), sum(fine_assessed) BY member_no
• JOINs - We are all family here
Joins allow you to retrieve columns from two or more tables usually within the same database, but also
among different databases.
1. Two types of JOINs ANSI - Join Operators: INNER JOIN, CROSS JOIN, LEFT/RIGHT/FULL OUTER
JOIN SQL Server - Join Operators: =,<>, *= and =*
2. Examples of SQL Server
SELECT pub_name, title
FROM titles
INNER JOIN publishers --Note: INNER is optional
ON titles.pub_id = publishers.pub_id
which produces:
mykey letter1 letter2
----------- ------- -------
1 a d
1 a e
1 a g
2 b d
2 b e
2 b g
3 c d
3 c e
3 c g
3. OUTER JOIN - three types
1. LEFT OUTER JOIN - selects all valid rows from the first table
SELECT table1.mykey,table1.letter1,table2.letter2
FROM table1
LEFT OUTER JOIN table2
ON table1.mykey = table2.mykey
2. RIGHT OUTER JOIN - selects all valid rows from the second table
SELECT table1.mykey,table1.letter1,table2.letter2
FROM table1
RIGHT OUTER JOIN table2
ON table1.mykey = table2.mykey
Then we execute,
SELECT table1.mykey,table1.letter1,table2.letter2,table3.letter3
FROM table1
FULL OUTER JOIN table2 ON table1.mykey = table2.mykey
FULL OUTER JOIN table3 ON table1.mykey = table3.mykey
Which yields:
• Subqueries
1. Three ways to connect queries with subqueries
1. =,>,< ...
2. IN
3. EXISTS
2. Example 1
--This is a 'classic' subquery.
--Show all titles that have a price
--larger than average of all titles.
USE pubs
SELECT price, title
FROM titles
WHERE price >
(SELECT AVG(price) FROM titles)
3. Example 2
SELECT title_id AS Title,
qty AS Quantity,
(SELECT SUM(qty) FROM sales) AS 'Total Sales',
(CONVERT(money,qty)/(SELECT SUM(qty) FROM sales))*100
AS '% of Total'
FROM sales
4. Example 3
SELECT title_id, title
FROM titles
WHERE title_id IN
(SELECT title_id FROM sales)
• Triggers
Triggers are bits of code that are executed when an operation occurs on a table. Triggers can be set for
INSERT,UPDATE, or DELETE
1. Example
CREATE TRIGGER deltrig
ON emp
FOR DELETE
AS
DECLARE @currentuser VARCHAR(30)
SELECT @currentuser = 'Sorry, ' + USER_NAME()
PRINT @currentuser
PRINT 'Employees can''t be deleted!'
ROLLBACK TRANSACTION
GO
2. Example - get info about a trigger
SELECT name, crdate
FROM sysobjects
WHERE type = 'TR'
IF (SELECT count(*)
FROM member, inserted
WHERE member.member_no = inserted.member_no) > 1
BEGIN
RAISERROR ('Transaction will not be processed. Two members cannot have
the same member_no.',10,1)
ROLLBACK TRANSACTION
END
ELSE
8. Example:
/*
** Auto generate a primary key value, if needed
** (A zero got in there because it is the default;
** ie, the user did not enter a member number.)
** Works only if one row at a time is being added.
*/
IF (SELECT count(*)
FROM member
WHERE member.member_no = 0) > 0
BEGIN
UPDATE member
SET member_no = (SELECT max(member_no) FROM member) + 1
WHERE member_no = 0
END
GO
• Data Integrity/IDENTITY
An identity forces SQL server to have a unique value in a field. The starting value and the increment value
can be set as follows
CREATE TABLE stores2
(
stor_id int identity(1000,10) NOT NULL , -- starts at 1000, increments by 10
stor_name varchar (40) NULL ,
)
To see the values of these,
SELECT IDENT_SEED('class'), IDENT_INCR('class') -- shows initial identity and increment
• to set directly an IDENTITY field (for testing etc to override defaults)
SET IDENTITY_INSERT [TableName] ON
Example:
SET IDENTITY_INSERT Pubs..class ON -- allows an identity to be inserted
• IDENTITYCOL is a keyword which substitues for the name of the identity column
SELECT MAX(IDENTITYCOL) FROM stores2
-- identitycol is a keyword refering to a tables' identity column
-- Defining constraints
Primary Key
Unique
Foreign Key
Default
Check
• Comments
Comments are surrounded with '/*' and '*/', but cannot, for some
bizzare reason contain a 'GO' command.
CONSTRAINT PK_Payroll
PRIMARY KEY CLUSTERED
(empno,checkno,paydate)
WITH FILLFACTOR=25,
CONSTRAINT FK_Payroll
FOREIGN KEY (empno) REFERENCES emp (empno)
)
-- must drop constraint before index
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'member_ident')
ALTER TABLE member
DROP CONSTRAINT member_ident
--
-- see your views:
SELECT name, crdate
FROM sysobjects
WHERE type = 'V'
sp_helptext managers
--This should fail the CHECK
INSERT INTO managers
VALUES ('999', 'GATES, BILL', 'MCT') -- fails because MCT != MANAGER
• OBJECT_ID()
1. How to conditionally delete a view
-- old style
IF EXISTS ( SELECT name FROM sysobjects
WHERE type = 'V' AND name = 'stuff' )
DROP VIEW stuff
-- new style
IF OBJECT_ID('stuff', 'V') IS NOT NULL
DROP VIEW stuff
go
2. How to conditionally delete a table
IF OBJECT_ID('traffic_data', 'U') IS NOT NULL
DROP TABLE traffic_data
GO
3. Common second parameters to OBJECT_ID()
/*
C = CHECK constraint
D = DEFAULT (constraint or stand-alone)
F = FOREIGN KEY constraint
PK = PRIMARY KEY constraint
P = SQL stored procedure
FN = SQL scalar function
U = Table (user-defined)
UQ = UNIQUE constraint
V = View
X = Extended stored procedure
*/
• Isolation levels via Table Hints
If the results of your queries do not always have to be perfect, you can increase query speed and reduce
contention by using "READ UNCOMMITTED", which does not lock a table during a SELECT and allows
"dirty" reads.
SELECT COUNT(*) FROM dbo.Authors WITH(NOLOCK)
This will not lock the table and make the query faster.
Use the following command to make an entire session use no locking
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
GO
• INDEXs
CREATE INDEX [CLUSTERED|NONCLUSTERED] name ON table (col1,col2,...)
SELECT *
FROM authors
WHERE au_id = '123-45-6789' --clustered index
SET SHOWPLAN OFF
GO
--
--------------
-- OPTIMIZER HINTS
--------------
SET SHOWPLAN ON
GO
SELECT au_lname, au_fname, phone
FROM authors (INDEX = 1) -- INDEX=0 is none, INDEX=indexname
WHERE au_lname = 'Smith'
SET SHOWPLAN OFF
GO
--------------
-- UPDATE STATISTICS -- updates statistics that the optimizer uses
to determine which index to use on a query
--------------
-- show fragmentation
DECLARE @tbl INT
SELECT @tbl = OBJECT_ID('sales')
DBCC SHOWCONTIG (@tbl)
------------- check databases
DBCC CHECKDB -- should be run once a week on all database,
-- should be done before a backup
--
daily - dump database, update statistics on all indexes
hourly - dump transaction log
weekly - drop and recreate indexes
-- show performance data
SET SHOWPLAN ON -- shows indexes being used
SET STATISTICS IO ON
SET STATISTICS TIME ON --
-- drop an index if it exists
IF EXISTS (SELECT name FROM sysindexes WHERE name = 'reserve_item_link')
DROP INDEX reservation.reserve_item_link
GO
SET NOCOUNT ON
GO
DECLARE @org VARCHAR(50)
DECLARE @own VARCHAR(50)
PRINT 'Whoever set up SQL Server for this class typed these in:'
PRINT ' '
SELECT 'Registered Organization is '+UPPER(@org)
SELECT 'Registered Owner is '+UPPER(@own)
******************************************************-
USE Library
SET NOCOUNT ON
SELECT @counter=0
OPEN micount
END
CLOSE micount
DEALLOCATE micount
-- RAISERROR
sp_addmessage 55555, 16, 'Mitchs test message',us_english ,true
RAISERROR(55555,16,1)
• Misc Tips
1. When SQLServer UPDATEs a row, it really deletes i replaces it with a new one
SELECT title,copy_no,due_date,DATEDIFF(DAY,due_date,GETDATE()) FROM overdue
WHERE DATEDIFF(DAY,due_date,GETDATE()) > 14
2. Finding gaps in a sequence
This finds any non-consecutive numbers in the userID column.
SELECT A.userID + 1
FROM SDRespondents AS A
WHERE NOT EXISTS (
SELECT B.userID FROM SDRespondents AS B
WHERE A.userID + 1 = B.userID)
GROUP BY A.userID;
3. Set a database to single use only.
This is useful in simulating database failure to stop general access to a database.
EXECUTE sp_dboption library, 'dbo use only', TRUE -- dbo user only
EXECUTE sp_dboption library, 'dbo use only', FALSE
or
alter database myDatabaseName set SINGLE_USER WITH ROLLBACK IMMEDIATE
alter database myDatabaseName set MULTI_USER
4. User Defined Datatypes (UDDT)
EXECUTE sp_addtype zipcode, 'char(10)'
EXECUTE sp_addtype phonenumber, 'char(13)', NULL
EXECUTE sp_droptype <typename> -- to get rid of it
to get a list of UDDT
sp_help
example:
CREATE TABLE member (
member_no member_no NOT NULL, -- member_no is a User Defined Data Type
lastname shortstring NOT NULL,
firstname shortstring NOT NULL,
middleinitial letter NULL,
photograph image NULL
)
USE MAster
EXECUTE sp_dboption mydb, 'trunc. log on chkpt.',true
to set SELECT into/bulkcopy
EXECUTE sp_dboption mydb, 'SELECT into/bulkcopy',true
chars are treated as varchar's if NULL is a possible value.
Binary Large OBject - BLOB
SET NOCOUNT ON --suppress 'rows affected' msg
SET NOCOUNT OFF
5. Logic don't use "= NULL" use "IS NULL" because its ANSI NULLs fail all comparisons "NULL =
NULL" is false Order of Presedence: (),NOT,AND,OR
6. the EXECUTE command can be used to build commands from parts
7. Example 1
create proc displaytable
@tbl varchar(30)
as
EXECUTE ('SELECT * FROM ' + @tbl)
8. Example 2
SELECT @cmd = "create database "+@projabbrev+" ON "+@datadevice+" = 6 LOG ON
"+@logdevice+" = 6"
SELECT @cmd
EXECUTE (@cmd)
9. Terms:
A batch is a set of one or more SQL statements submitted together and executed as a single group. A
script is a series of one or more batches submitted one after the other. A script is a file, with a default
extension of .SQL Comparison operators (=,<>,>,<,>=,<=), BETWEEN, IN, LIKE, IS NULL, and IS NOT
NULL
10. The System supplied databases.
Database Function
Master: Controls all user databases and SQL Server as a whole
Model: Serves as a template when creating new user databases
Msdb: Provides support for the SQL Executive service
Tempdb: Used for temporary working storage for all connections
pubs: A sample database
2.
Allocation Unit: 1/2MB increments of database storage space
Extent: Eight 2K pages of table or index storage space
Page: The basic unit of I/O in SQL Server (2K in size)
11.Cursors
--deleteViews
-- This deletes all views which start with an X
-- trivial example of using cursors in sql server 6.5
IF EXISTS ( SELECT name FROM sysobjects
WHERE type = 'P' AND name = 'deleteViews' )
DROP PROCEDURE deleteViews
go
******************----------------
GO
SELECT @sqls = 'DECLARE view_cursor CURSOR FOR SELECT name FROM '
+ @databasename + '..sysobjects WHERE type = ''v'' and name LIKE ''X%'' '
--
exec(@sqls)
OPEN view_cursor
FETCH NEXT FROM view_cursor INTO @viewname
WHILE (@@FETCH_STATUS=0)
BEGIN
SELECT @fullviewname = @databasename + '..' + @viewname
SELECT 'current viewname is ' + @fullviewname
--EXEC ('DROP VIEW ' + @fullviewname)
K( Now) U R
DBDeveloper