51
SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 1 C hapter13 How to code scripts

SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

Embed Size (px)

DESCRIPTION

SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 3

Citation preview

Page 1: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 1

Chapter 13

How to codescripts

Page 2: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 2

Objectives

Applied objectives Given a Transact-SQL script written as a single batch, insert GO

commands to divide the script into appropriate batches. Given the specification for a database problem, write a script that

solves it. Use OSQL to execute a query against a database.

Knowledge objectives Explain the scope of a local variable. Describe the difference between a scalar variable and a table

variable. Compare and contrast the scopes of temporary tables, table

variables, and derived tables.

Page 3: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 3

Objectives (continued) Describe the difference between dynamic SQL and ordinary SQL

code. Given a Transact-SQL script, explain what each statement does.

Page 4: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 4

A script with two batches (part 1)/*Creates three tables in a database named ClubRoster.

Author: Bryan SyversonCreated: 2002-08-12Modified: 2002-09-26*/

CREATE DATABASE ClubRosterGO

USE ClubRoster

CREATE TABLE Members(MemberID int NOT NULL IDENTITY PRIMARY KEY,LastName varchar(75) NOT NULL,FirstName varchar(50) NOT NULL,MiddleName varchar(50) NULL)

Page 5: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 5

A script with two batches (part 2)CREATE TABLE Committees(CommitteeID int NOT NULL IDENTITY PRIMARY KEY,CommitteeName varchar(50) NOT NULL)

CREATE TABLE CommitteeAssignments(MemberID int NOT NULL REFERENCES Members(MemberID),CommitteeID int NOT NULL REFERENCESCommittees(CommitteeID))

Statements that must be in their own batchCREATE VIEWCREATE PROCEDURECREATE FUNCTIONCREATE TRIGGER

Page 6: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 6

How to work with scripts A script is a series of SQL statements that you can store in a file. A script can contain one or more batches that execute as a unit. To signal the end of a batch, you use the GO command. A GO

command isn’t required after the last batch in a script or for a script that contains a single batch.

If a statement must be executed before the statements that follow can succeed, you should include a GO command after it.

If you create a database within a script, you have to execute the batch that contains the CREATE DATABASE statement before you can execute other statements that refer to the database.

Within a batch, the statements are executed in sequence, so be sure to code them in a logical order.

If a script will be used with a production database, you should include comments to document its function, creation details, etc.

Page 7: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 7

An introduction to the Transact-SQL statementsfor script processing Transact-SQL provides statements that are used within SQL

scripts. These statements add functionality similar to that provided by

procedural programming languages. These statements are part of the Transact-SQL, or T-SQL, language

and aren’t available on SQL-based systems other than SQL Server.

Page 8: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 8

Transact-SQL statements for controlling theflow of executionKeyword DescriptionIF...ELSE Controls the flow of execution based on a

condition.BEGIN...END Defines a statement block.WHILE Repeats statements while a specific condition is

true.BREAK Exits the innermost WHILE loop.CONTINUE Returns to the beginning of a WHILE loop.GOTO Unconditionally changes the flow of execution.RETURN Exits unconditionally.

Page 9: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 9

Other Transact-SQL statements for scriptprocessingKeyword DescriptionUSE Changes the database context to the specified

database.PRINT Returns a message to the client.DECLARE Declares a local variable.SET Sets the value of a local variable or a session

variable.EXEC Executes a dynamic SQL statement or stored

procedure.

Page 10: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 10

The syntax of the USE statementUSE database

The syntax of the PRINT statementPRINT string_expression

A script that uses some of the T-SQL statementsUSE APDECLARE @TotalDue moneySET @TotalDue = (SELECT SUM(InvoiceTotal - PaymentTotal – CreditTotal) FROM Invoices)IF @TotalDue > 0 PRINT 'Total invoices due = $' +CONVERT(varchar,@TotalDue,1)ELSE PRINT 'Invoices paid in full'

Page 11: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 11

The syntax of the DECLARE statement for scalarvariables

DECLARE @variable_name_1 data_type [, @variable_name_2 data_type]...

The syntax of the SET statement for a scalarvariable

SET @variable_name = expression

An alternate syntax for setting a variable’s valuein a select list

SELECT @variable_name = column_specification

Page 12: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 12

How to work with scalar values A variable is used to store data. To create a variable, you use the DECLARE statement. The initial

value of a variable is always null. A variable that’s defined with a standard data type contains a

single value and is called a scalar variable. Whenever possible, you should use long, descriptive names for

variables. The name of a variable must start with an at sign (@). The scope of a variable is the batch in which it’s defined, which

means that it can’t be referred to from outside that batch. Becauseof that, variables are often called local variables.

To assign a value to a variable, you can use the SET statement forone variable or the SELECT statement for one or more variables.

You can use a variable in any expression, but you can’t use it inplace of an object name or a keyword.

Page 13: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 13

A SQL script that uses variables (part 1)USE AP

DECLARE @MaxInvoice money, @MinInvoice moneyDECLARE @PercentDifference decimal(8,2)DECLARE @InvoiceCount int, @VendorIDVar int

SET @VendorIDVar = 95SET @MaxInvoice = (SELECT MAX(InvoiceTotal) FROM Invoices WHERE VendorID = @VendorIDVar)SELECT @MinInvoice = MIN(InvoiceTotal), @InvoiceCount = COUNT(*)FROM InvoicesWHERE VendorID = @VendorIDVarSET @PercentDifference = (@MaxInvoice - @MinInvoice) / @MinInvoice * 100

Page 14: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 14

A SQL script that uses variables (part 2)PRINT 'Maximum invoice is $' +CONVERT(varchar,@MaxInvoice,1) + '.'PRINT 'Minimum invoice is $' +CONVERT(varchar,@MinInvoice,1) + '.'PRINT 'Maximum is ' +CONVERT(varchar,@PercentDifference) + '% more than minimum.'PRINT 'Number of invoices: ' + CONVERT(varchar,@InvoiceCount) + '.'

The response from the systemMaximum invoice is $46.21.Minimum invoice is $16.33.Maximum is 182.97% more than minimum.Number of invoices: 6.

Page 15: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 15

The syntax of the DECLARE statement for a tablevariable

DECLARE @table_name TABLE(column_name_1 data_type [column_attributes][, column_name_2 data_type [column_attributes]]...[, table_attributes])

Page 16: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 16

How to work with table variables A table variable can store an entire result set rather than a single

value. To create a table variable, use a DECLARE statement with the

table data type. You use the same syntax for defining the columns of a table

variable as you do for defining a new table with the CREATETABLE statement.

Like a scalar variable, a table variable has local scope, so it’savailable only within the batch where it’s declared.

You can use a table variable like a standard table within SELECT,INSERT, UPDATE, and DELETE statements.

You can’t use a table variable within the INTO clause of aSELECT INTO statement.

Page 17: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 17

A SQL script that uses a table variableUSE AP

DECLARE @BigVendors table(VendorID int,VendorName varchar(50))

INSERT @BigVendorsSELECT VendorID, VendorNameFROM VendorsWHERE VendorID IN (SELECT VendorID FROM Invoices WHERE InvoiceTotal > 5000)

SELECT * FROM @BigVendors

The result set

Page 18: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 18

How to work with temporary tables A temporary table exists only during the current database session. In the Query Analyzer, a temporary table is available until you

close the window where you created the table. Temporary tables are useful for testing queries or for storing data

temporarily in a complex script. A local temporary table is visible only within the current session,

but a global temporary table is visible to all sessions. To identify a local temporary table, you prefix the name with a

number sign ( # ). To identify a global temporary table, you prefixthe name with two number signs ( ## ).

If you need to drop a temporary table before the end of the currentsession, you can do that using the DROP TABLE statement.

Temporary tables are stored in the system database named tempdb.

Page 19: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 19

A script that uses a local temporary table insteadof a derived table

SELECT TOP 1 VendorID, AVG(InvoiceTotal) AS AvgInvoiceINTO #TopVendorsFROM InvoicesGROUP BY VendorIDORDER BY AvgInvoice DESC

SELECT Invoices.VendorID, MAX(InvoiceDate) AS LatestInvFROM Invoices JOIN #TopVendors ON Invoices.VendorID = #TopVendors.VendorIDGROUP BY Invoices.VendorID

The result set

Page 20: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 20

A script that creates a global temporary table ofrandom numbers

CREATE TABLE ##RandomSSNs(SSN_ID int IDENTITY,SSN char(9) DEFAULT LEFT(CAST(CAST(CEILING(RAND()*10000000000) AS bigint)AS varchar),9))

INSERT ##RandomSSNs VALUES (DEFAULT)INSERT ##RandomSSNs VALUES (DEFAULT)

SELECT * FROM ##RandomSSNs

The result set

Page 21: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 21

The five types of Transact-SQL table objectsType ScopeStandard table Available within the system until explicitly

deleted.Temporary table Available within the system while the current

database session is open.Table variable Available within a script while the current

batch is executing.Derived table Available within a statement while the current

statement is executing.View Available within the system until explicitly

deleted.

Page 22: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 22

A comparison of the five types of Transact-SQLtables Within a Transact-SQL script, you often need to work with table

objects other than the base tables in your database. The scope of a table object determines what code in the script has

access to that table. Standard tables and views are stored permanently on disk until they

are explicitly deleted, so they have the broadest scope and aretherefore always available for use.

Derived tables and table variables are generally stored in memory,so they can provide the best performance.

Standard tables and temporary tables are always stored on disk andtherefore provide slower performance.

Page 23: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 23

A comparison of the five types of Transact-SQLtables (continued) While a derived table provides better performance, if you need to

use the table in other batches, create a temporary table. If the data needs to be available to other connections to the

database, create a standard table or, if possible, a view. Views provide fast performance since they’re predefined, and high

availability since they’re permanent objects. So you should use aview rather than create a table object whenever that’s possible.

However, you can’t use a view if you need to insert, delete, orupdate the data in the table object without affecting the base tablesof your database.

Page 24: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 24

The syntax of the IF...ELSE statement IF expression {statement|BEGIN...END} [ELSE {statement|BEGIN...END}]

How to perform conditional processing You use the IF…ELSE statement to test a conditional expression. If the expression is true, the statements that follow the IF keyword

are executed. Otherwise, the statements that follow the ELSE keyword are executed if that keyword is included.

If you need to execute two or more SQL statements within an IF or ELSE clause, enclose them within a BEGIN…END block.

You can nest IF...ELSE statements within other IF...ELSE statements. Although SQL Server doesn’t limit the number of nested levels, you should avoid nesting so deeply that your script becomes difficult to read.

Page 25: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 25

A script that tests for outstanding invoices withan IF statement

USE APDECLARE @EarliestInvoiceDue smalldatetimeSELECT @EarliestInvoiceDue = MIN(InvoiceDueDate) FROM Invoices WHERE InvoiceTotal - PaymentTotal - CreditTotal > 0IF @EarliestInvoiceDue < GETDATE() PRINT 'Outstanding invoices overdue!'

The response from the systemOutstanding invoices overdue!

Page 26: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 26

An enhanced version of the same script that usesan IF...ELSE statement (part 1)

USE APDECLARE @MinInvoiceDue money, @MaxInvoiceDue moneyDECLARE @EarliestInvoiceDue smalldatetime, @LatestInvoiceDue smalldatetimeSELECT @MinInvoiceDue = MIN(InvoiceTotal – PaymentTotal – CreditTotal), @MaxInvoiceDue = MAX(InvoiceTotal – PaymentTotal - CreditTotal), @EarliestInvoiceDue = MIN(InvoiceDueDate), @LatestInvoiceDue = MAX(InvoiceDueDate)FROM InvoicesWHERE InvoiceTotal – PaymentTotal - CreditTotal > 0

Page 27: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 27

An enhanced version of the same script that usesan IF...ELSE statement (part 2)

IF @EarliestInvoiceDue < GETDATE() BEGIN PRINT 'Outstanding invoices overdue!' PRINT 'Dated ' + CONVERT(varchar,@EarliestInvoiceDue,1) + ' through ' + CONVERT(varchar,@LatestInvoiceDue,1) + '.' PRINT 'Amounting from $' + CONVERT(varchar,@MinInvoiceDue,1) + ' to $' + CONVERT(varchar,@MaxInvoiceDue,1) + '.' ENDELSE --@EarliestInvoiceDue >= GETDATE() PRINT 'No overdue invoices.'

The response from the systemOutstanding invoices overdue!Dated 06/09/02 through 07/20/02.Amounting from $6.00 to $21,842.00.

Page 28: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 28

The syntax of the OBJECT_ID functionOBJECT_ID('object')

The syntax of the DB_ID functionDB_ID('database')

How to test for the existence of a database object Before you work with an object in a database, you’ll want to be

sure that it exists. Similarly, before you create an object in adatabase, you’ll want to be sure that it doesn’t already exist.

You use the OBJECT_ID function to check for the existence of atable, view, stored procedure, user-defined function, or trigger.

You use the DB_ID function to check for the existence of adatabase.

Both functions return a null value if the object doesn’t exist.Otherwise, they return the object’s identification number.

Page 29: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 29

Examples that use the OBJECT_ID and DB_IDfunctions

Code that tests whether a database exists beforedeleting itUSE masterIF DB_ID('TestDB') IS NOT NULL DROP DATABASE TestDBCREATE DATABASE TestDB

Code that tests for the existence of a tableIF OBJECT_ID('InvoiceCopy') IS NOT NULL DROP TABLE InvoiceCopy

Another way to test for the existence of a tableIF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE (TABLE_NAME = 'InvoiceCopy' AND TABLE_TYPE = 'BASE TABLE')) DROP TABLE InvoiceCopy

Page 30: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 30

Examples that use the OBJECT_ID and DB_IDfunctions (continued)

Code that tests for the existence of a temporary tableIF OBJECT_ID('tempdb..#AllUserTables') IS NOT NULL DROP TABLE #AllUserTables

Note To test for the existence of a temporary table, you must qualify the

table name with the database that contains it: tempdb. Since this isa system database, you can omit the owner name.

Page 31: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 31

The syntax of the WHILE statementWHILE expression {statement|BEGIN...END} [BREAK] [CONTINUE]

How to perform repetitive processing To execute a SQL statement repeatedly, you use the WHILE

statement. This statement is executed as long as the conditionalexpression in the WHILE clause is true.

If you need to execute two or more SQL statements within aWHILE loop, enclose them within a BEGIN…END block.

To exit from a WHILE loop immediately without testing theexpression, use the BREAK statement.

To return to the beginning of a WHILE loop without executingany additional statements in the loop, use the CONTINUEstatement.

Page 32: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 32

A script that tests and adjusts credit amounts witha WHILE loop (part 1)

USE APIF OBJECT_ID('tempdb..#InvoiceCopy') IS NOT NULL DROP TABLE #InvoiceCopySELECT * INTO #InvoiceCopy FROM InvoicesWHERE (InvoiceTotal – CreditTotal - PaymentTotal) > 0

WHILE (SELECT SUM(InvoiceTotal - CreditTotal – PaymentTotal) FROM #InvoiceCopy) >= 50000 BEGIN UPDATE #InvoiceCopy SET CreditTotal = CreditTotal + .01 WHERE InvoiceTotal – CreditTotal - PaymentTotal > 0 IF (SELECT MAX(CreditTotal) FROM #InvoiceCopy) > 3000 BREAK ELSE CONTINUE END

Page 33: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 33

A script that tests and adjusts credit amountswith a WHILE loop (part 2)

SELECT InvoiceDate, InvoiceTotal, CreditTotalFROM #InvoiceCopy

The result set

Page 34: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 34

How to use the system functions The system functions return information about SQL Server values,

objects, and settings. A system function can be used anywhere an expression is allowed. System functions are useful in writing scripts. In addition, some of

them can be used to provide a value for a DEFAULT constraint ona column.

System functions used to be called global variables, but that nameis no longer used.

Usually, it’s better to store the value returned by a system functionin a variable than to use the function directly because the value ofthe function can change when subsequent statements are executed.

Page 35: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 35

Some of the Transact-SQL system functionsFunction name Description@@IDENTITY Returns the last value generated for an identity

column on the server. Returns NULL if noidentity value was generated.

IDENT_CURRENT ('tablename')

Similar to @@IDENTITY, but returns the lastidentity value generated for a specified table.

@@ROWCOUNT Returns the number of rows affected by themost recent SQL statement.

@@ERROR Returns the error number generated by theexecution of the most recent SQL statement.Returns 0 if no error occurred.

@@SERVERNAME Returns the name of the local server.HOST_NAME() Returns the name of the current workstation.SYSTEM_USER Returns the name of the current user.

Page 36: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 36

A script that inserts a new vendor and a newinvoice

USE APDECLARE @MyIdentity int, @MyRowCount int

INSERT Vendors (VendorName, VendorAddress1, VendorCity, VendorState, VendorZipCode, VendorPhone, DefaultTermsID, DefaultAccountNo)VALUES ('Peerless Binding', '1112 S Windsor St', 'Hallowell', 'ME', '04347', '(207) 555-1555', 4, 400)

SET @MyIdentity = @@IDENTITYSET @MyRowCount = @@ROWCOUNT

IF @MyRowCount = 1 INSERT Invoices VALUES (@MyIdentity, 'BA-0199', '2001-08-01', 4598.23, 0, 0, 4, '2001-09-06', NULL)

The response from the system(1 row(s) affected)(1 row(s) affected)

Page 37: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 37

Transact-SQL statements for changing sessionsettingsStatement DescriptionSET DATEFORMAT format Sets the order of the parts of a date

(month/day/year) for entering date/timedata. The default is mdy.

SET NOCOUNT {ON|OFF} Determines whether SQL Server returnsa message indicating the number ofrows that were affected by a statement.OFF is the default.

SET ANSI_NULLS {ON|OFF} Determines how SQL Server handlesequals and not equals comparisons withnull values. The default is ON, in whichcase “WHERE column = NULL” willalways return an empty result set, evenif there are null values in the column.

Page 38: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 38

Transact-SQL statements for changing sessionsettings (continued)Statement DescriptionSET ANSI_PADDING{ON|OFF}

Determines how SQL Server stores char andvarchar values that are smaller than thecolumn length or that contain trailingblanks. The default is ON, which meanschar values are padded with blanks andtrailing blanks in varchar values are nottrimmed. OFF means that char values thatdon’t allow nulls are padded with blanks,but blanks are trimmed from char valuesthat allow nulls amd from varchar values.

SET ROWCOUNT number Limits the number of rows that areprocessed by a query. The default setting is0, which causes all rows to be processed.

Page 39: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 39

How to change the session settings You use the SET statement to change configuration settings for the

current session. These settings control the way queries and scriptsexecute.

If the ANSI_NULLS option is set to ON, you can only test for nullvalues in a column by using the IS NULL clause.

Instead of using the SET ROWCOUNT statement to limit thenumbers of rows that are processed by a query, you should use theTOP clause.

A statement that changes the date formatSET DATEFORMAT ymd

Page 40: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 40

The syntax of the EXEC statement{EXEC|EXECUTE} ('SQL_string')

How to use dynamic SQL The EXEC statement executes the SQL statement contained in a

string. Because you define the SQL string within the script, you can create

and execute SQL code that changes each time the script is run.This is called dynamic SQL.

You can use dynamic SQL to perform operations that can’t beaccomplished using any other technique.

Page 41: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 41

A script that uses an EXEC statementUSE APDECLARE @TableNameVar varchar(128)SET @TableNameVar = 'Invoices'EXEC ('SELECT * FROM ' + @TableNameVar)

The contents of the SQL string at executionSELECT * FROM Invoices

Page 42: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 42

A script that creates a table with one column foreach vendor with a balance due (part 1)

USE APDECLARE @DynamicSQL varchar(8000)

IF OBJECT_ID('XtabVendors') IS NOT NULL DROP TABLE XtabVendors

SET @DynamicSQL = 'CREATE TABLE XtabVendors (' SELECT @DynamicSQL = @DynamicSQL + '[' + VendorName + '] bit,' FROM Vendors WHERE VendorID IN (SELECT VendorID FROM Invoices WHERE InvoiceTotal - CreditTotal - PaymentTotal > 0) ORDER BY VendorNameSET @DynamicSQL = @DynamicSQL + ')'

EXEC (@DynamicSQL)SELECT * FROM XtabVendors

Page 43: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 43

A script that creates a table with one column foreach vendor with a balance due (part 2)

The contents of the SQL string that’s created by the scriptCREATE TABLE XtabVendors ([Abbey Office Furnishings]bit,[Blue Cross] bit,[Cardinal Business Media, Inc.]bit,[Coffee Break Service] bit,[Compuserve]bit,[Computerworld] bit,[Data Reproductions Corp]bit,[Federal Express Corporation] bit,[Ford Motor CreditCompany] bit,[Ingram] bit,[Malloy Lithographing Inc]bit,[Pacific Bell] bit,[Roadway Package System, Inc]bit,[United Parcel Service] bit,[Wells Fargo Bank]bit,[Zylka Design] bit,)

The result set

Page 44: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 44

A script that creates a summary of the tables in adatabase (part 1)

/*Creates and queries a table, #TableSummary, that liststhe columns for each user table in the database, plusthe number of rows in each table.

Author: Bryan SyversonCreated: 2002-07-02Modified: 2002-07-16*/

USE AP

IF OBJECT_ID('tempdb..#TableSummary') IS NOT NULL DROP TABLE #TableSummary

Page 45: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 45

A script that creates a summary of the tables in adatabase (part 2)

SELECT TABLE_NAME AS TableName, COLUMN_NAME AS ColumnName, DATA_TYPE AS TypeINTO #TableSummaryFROM INFORMATION_SCHEMA.COLUMNSWHERE TABLE_NAME IN (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE (TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME NOT IN ('dtproperties', 'TableSummary', 'AllUserTables')))

IF OBJECT_ID('tempdb..#AllUserTables') IS NOT NULL DROP TABLE #AllUserTables

CREATE TABLE #AllUserTables(TableID int IDENTITY, TableName varchar(128))GO

Page 46: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 46

A script that creates a summary of the tables in adatabase (part 3)

INSERT #AllUserTables (TableName)SELECT TABLE_NAMEFROM INFORMATION_SCHEMA.TABLESWHERE (TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME NOT IN ('dtproperties', 'TableSummary', 'AllUserTables'))

DECLARE @LoopMax int, @LoopVar intDECLARE @TableNameVar varchar(128), @ExecVar varchar(1000)

SELECT @LoopMax = MAX(TableID) FROM #AllUserTables

SET @LoopVar = 1

Page 47: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 47

A script that creates a summary of the tables in adatabase (part 4)

WHILE @LoopVar <= @LoopMax BEGIN SELECT @TableNameVar = TableName FROM #AllUserTables WHERE TableID = @LoopVar SET @ExecVar = 'DECLARE @CountVar int ' SET @ExecVar = @ExecVar + 'SELECT @CountVar = COUNT(*) ' SET @ExecVar = @ExecVar + 'FROM ' + @TableNameVar + ' ' SET @ExecVar = @ExecVar + 'INSERT #TableSummary ' SET @ExecVar = @ExecVar + 'VALUES (''' + @TableNameVar + ''',' SET @ExecVar = @ExecVar + '''*Row Count*'',' SET @ExecVar = @ExecVar + ' @CountVar)' EXEC (@ExecVar) SET @LoopVar = @LoopVar + 1 END

Page 48: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 48

A script that creates a summary of the tables in adatabase (part 5)

SELECT * FROM #TableSummaryORDER BY TableName, ColumnName

The contents of the SQL string for one iteration of theloopDECLARE @CountVar int SELECT @CountVar = COUNT(*) FROMContactUpdates INSERT #TableSummary VALUES('ContactUpdates','*Row Count*', @CountVar)

The result set

Page 49: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 49

A Command Prompt window running OSQL

Page 50: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 50

How to use OSQL OSQL is a utility that runs T-SQL scripts from a command line. To open a command prompt window where you can start OSQL,

select StartProgramsAccessoriesCommand Prompt. Whenyou’re done, enter “exit.”

To start an OSQL session, enter the OSQL command at the C:\>prompt along with the appropriate command line switches.

Once you’re running OSQL, enter the statements you want toexecute followed by the GO command, or use one of the commandline switches.

To exit from OSQL, enter the Exit command.

Page 51: SQL for SQL Server, C13© 2002, Mike Murach & Associates, Inc.Slide 1

SQL for SQL Server, C13 © 2002, Mike Murach & Associates, Inc. Slide 51

Command line switchesSwitch Function-? Show a summary of all command line switches.-E Use a trusted connection (Windows

authentication mode).-L List the names of the available servers.-S server_name Log in to a specific server.-U user_name Log in as a specific user (SQL Server

authentication mode).-P password Specify the password in the command line (SQL

Server authentication mode).-Q "query" Execute the specified query, then exit.-i file_name Specify the name of the script file to be executed.-o file_name Specify a file in which to save system responses.