truncate table
TRANSCRIPT
-
8/7/2019 TRUNCATE TABLE
1/25
TRUNCATE TABLE
SQL Server 2000
Removes all rows from a table without logging the individual row deletes.
Syntax
TRUNCATE TABLE name
Arguments
name
Is the name of the table to truncate or from which all rows are removed.
Remarks
TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause:both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system andtransaction log resources than DELETE.
The DELETE statement removes rows one at a time and records an entry in the transaction logfor each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages usedto store the table's data, and only the page deallocations are recorded in the transaction log.
TRUNCATE TABLE removes all rows from a table, but the table structure and its columns,
constraints, indexes and so on remain. The counter used by an identity for new rows is reset tothe seed for the column. If you want to retain the identity counter, use DELETE instead. If youwant to remove table definition and its data, use the DROP TABLE statement.
You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint;instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is notlogged, it cannot activate a trigger.
TRUNCATE TABLE may not be used on tables participating in an indexed view.
Examples
This example removes all data from the authors table.
TRUNCATE TABLE authors
Permissions
-
8/7/2019 TRUNCATE TABLE
2/25
TRUNCATE TABLE permissions default to the table owner, members of the sysadmin fixedserver role, and the db_owner and db_ddladmin fixed database roles, and are not transferable.
QUOTENAME
SQL Server 2000
Returns a Unicode string with the delimiters added to make the input string a valid MicrosoftSQL Server delimited identifier.
Syntax
QUOTENAME ( 'character_string' [ , 'quote_character' ] )
Arguments
'character_string'
Is a string of Unicode character data. character_stringis sysname.
'quote_character'
Is a one-character string to use as the delimiter. Can be a single quotation mark ('), a left or rightbracket ([]), or a double quotation mark ("). Ifquote_characteris not specified, brackets areused.
Return Types
nvarchar(258)
Examples
This example takes the character string abc[]def and uses the [ and ] characters to create a validSQL Server quoted (delimited) identifier.
SELECT QUOTENAME('abc[]def')
-
8/7/2019 TRUNCATE TABLE
3/25
Here is the result set:
[abc[]]def]
(1 row(s) affected)
Notice that the right bracket in the string abc[]def is doubled to indicate an escape character.
DIFFERENCE
SQL Server 2000
Topic last updated -- July 2003
Returns the difference between the SOUNDEX values of two character expressions as an integer.
Syntax
DIFFERENCE ( character_expression ,character_expression )
Arguments
character_expression
Is an expression of type char orvarchar. character_expression can also be of type text;however, only the first 8,000 bytes are significant.
Return Types
int
Remarks
-
8/7/2019 TRUNCATE TABLE
4/25
The integer returned is the number of characters in the SOUNDEX values that are the same. Thereturn value ranges from 0 through 4: 0 indicates little or no similarity, and 4 indicates strongsimilarity or identical values.
Examples
In the first part of this example, the SOUNDEX values of two very similar strings are compared,and DIFFERENCE returns a value of 4. In the second part of this example, the SOUNDEXvalues for two very different strings are compared, and DIFFERENCE returns a value of 0.
USE pubsGO-- Returns a DIFFERENCE value of 4, the least possible difference.SELECT SOUNDEX('Green'),SOUNDEX('Greene'), DIFFERENCE('Green','Greene')
GO-- Returns a DIFFERENCE value of 0, the highest possible difference.SELECT SOUNDEX('Blotchet-Halls'),
SOUNDEX('Greene'), DIFFERENCE('Blotchet-Halls', 'Greene')GO
Here is the result set:
----- ----- -----------G650 G650 4
(1 row(s) affected)----- ----- -----------B432 G650 0
(1 row(s) affected)
@@ROWCOUNTSQL Server 2000
Topic last updated -- July 2003
Returns the number of rows affected by the last statement.
-
8/7/2019 TRUNCATE TABLE
5/25
Syntax
@@ROWCOUNT
Return Types
integer
Remarks
This variable is set to 0 by any statement that does not return rows, such as an IF statement.
If the table has more than 2 billion rows, use ROWCOUNT_BIG(). For more information, seeROWCOUNT_BIG().
Examples
This example executes UPDATE and uses @@ROWCOUNT to detect if any rows werechanged.
UPDATE authors SET au_lname = 'Jones'WHERE au_id = '999-888-7777'IF @@ROWCOUNT = 0
print 'Warning: No rows were updated'
SOUNDEX
SQL Server 2000
Returns a four-character (SOUNDEX) code to evaluate the similarity of two strings.
http://msdn.microsoft.com/en-us/library/aa238380(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa238380(v=SQL.80).aspx -
8/7/2019 TRUNCATE TABLE
6/25
Syntax
SOUNDEX ( character_expression )
Arguments
character_expression
Is an alphanumeric expression of character data. character_expression can be a constant,variable, or column.
Return Types
char
Remarks
SOUNDEX converts an alpha string to a four-character code to find similar-sounding words ornames. The first character of the code is the first character ofcharacter_expression and thesecond through fourth characters of the code are numbers. Vowels in character_expression areignored unless they are the first letter of the string. String functions can be nested.
Examples
This example shows the SOUNDEX function and the related DIFFERENCE function. In the firstexample, the standard SOUNDEX values are returned for all consonants. Returning theSOUNDEX for Smith and Smythe returns the same SOUNDEX result because all vowels, theletter y, doubled letters, and the letter h, are not included.
-- Using SOUNDEXSELECT SOUNDEX ('Smith'), SOUNDEX ('Smythe')
Here is the result set:
----- -----S530 S530
(1 row(s) affected)
The DIFFERENCE function compares the difference of the SOUNDEX pattern results. The first
example shows two strings that differ only in vowels. The difference returned is 4 (lowestpossible difference).
-- Using DIFFERENCESELECT DIFFERENCE('Smithers', 'Smythers')GO
Here is the result set:
-
8/7/2019 TRUNCATE TABLE
7/25
-----------4
(1 row(s) affected)
In this example, the strings differ in consonants, so the difference returned is 2 (higher
difference).
SELECT DIFFERENCE('Anothers', 'Brothers')GO
Here is the result set:
-----------2
(1 row(s) affected)
@@ERRORSQL Server 2000
Returns the error number for the last Transact-SQL statement executed.
Syntax
@@ERROR
Return Types
integer
Remarks
When Microsoft SQL Server completes the execution of a Transact-SQL statement,@@ERROR is set to 0 if the statement executed successfully. If an error occurs, an errormessage is returned. @@ERROR returns the number of the error message until another
-
8/7/2019 TRUNCATE TABLE
8/25
Transact-SQL statement is executed. You can view the text associated with an @@ERROR errornumber in the sysmessages system table.
Because @@ERROR is cleared and reset on each statement executed, check it immediatelyfollowing the statement validated, or save it to a local variable that can be checked later.
Examples
A. Use @@ERROR to detect a specific error
This example uses @@ERROR to check for a check constraint violation (error #547) in anUPDATE statement.
USE pubsGOUPDATE authors SET au_id = '172 32 1176'WHERE au_id = "172-32-1176"
IF @@ERROR = 547print "A check constraint violation occurred"
B. Use @@ERROR to conditionally exit a procedure
The IF...ELSE statements in this example test @@ERROR after an INSERT statement in astored procedure. The value of the @@ERROR variable determines the return code sent to thecalling program, indicating success or failure of the procedure.
USE pubsGO
-- Create the procedure.CREATE PROCEDURE add_author@au_id varchar(11),@au_lname varchar(40),@au_fname varchar(20),@phone char(12),@address varchar(40) = NULL,@city varchar(20) = NULL,@state char(2) = NULL,@zip char(5) = NULL,@contract bit = NULLAS
-- Execute the INSERT statement.INSERT INTO authors(au_id, au_lname, au_fname, phone, address,city, state, zip, contract) values
(@au_id,@au_lname,@au_fname,@phone,@address,@city,@state,@zip,@contract)
-- Test the error value.IF @@ERROR 0BEGIN
-- Return 99 to the calling program to indicate failure.PRINT "An error occurred loading the new author information"RETURN(99)
END
-
8/7/2019 TRUNCATE TABLE
9/25
ELSEBEGIN
-- Return 0 to the calling program to indicate success.PRINT "The new author information has been loaded"RETURN(0)
ENDGO
C. Use @@ERROR to check the success of several statements
This example depends on the successful operation of the INSERT and DELETE statements.Local variables are set to the value of @@ERROR after both statements and are used in a sharederror-handling routine for the operation.
USE pubsGODECLARE @del_error int, @ins_error int-- Start a transaction.BEGIN TRAN
-- Execute the DELETE statement.DELETE authorsWHERE au_id = '409-56-7088'
-- Set a variable to the error value for-- the DELETE statement.SELECT @del_error = @@ERROR
-- Execute the INSERT statement.INSERT authors
VALUES('409-56-7008', 'Bennet', 'Abraham', '415 658-9932','6223 Bateman St.', 'Berkeley', 'CA', '94705', 1)
-- Set a variable to the error value for-- the INSERT statement.SELECT @ins_error = @@ERROR
-- Test the error values.IF @del_error = 0 AND @ins_error = 0BEGIN
-- Success. Commit the transaction.PRINT "The author information has been replaced"COMMIT TRAN
ENDELSEBEGIN
-- An error occurred. Indicate which operation(s) failed
-- and roll back the transaction.IF @del_error 0
PRINT "An error occurred during execution of the DELETEstatement."
IF @ins_error 0PRINT "An error occurred during execution of the INSERTstatement."
-
8/7/2019 TRUNCATE TABLE
10/25
ROLLBACK TRANENDGO
D. Use @@ERROR with @@ROWCOUNT
This example uses @@ERROR with @@ROWCOUNT to validate the operation of anUPDATE statement. The value of @@ERROR is checked for any indication of an error, and@@ROWCOUNT is used to ensure that the update was successfully applied to a row in thetable.
USE pubsGOCREATE PROCEDURE change_publisher@title_id tid,@new_pub_id char(4)AS
-- Declare variables used in error checking.DECLARE @error_var int, @rowcount_var int
-- Execute the UPDATE statement.UPDATE titles SET pub_id = @new_pub_idWHERE title_id = @title_id
-- Save the @@ERROR and @@ROWCOUNT values in local-- variables before they are cleared.SELECT @error_var = @@ERROR, @rowcount_var = @@ROWCOUNT
-- Check for errors. If an invalid @new_pub_id was specified-- the UPDATE statement returns a foreign-key violation error #547.IF @error_var 0
BEGINIF @error_var = 547BEGIN
PRINT "ERROR: Invalid ID specified for new publisher"RETURN(1)
ENDELSEBEGIN
PRINT "ERROR: Unhandled error occurred"RETURN(2)
ENDEND
-- Check the rowcount. @rowcount_var is set to 0-- if an invalid @title_id was specified.IF @rowcount_var = 0BEGIN
PRINT "Warning: The title_id specified is not valid"RETURN(1)
ENDELSEBEGIN
PRINT "The book has been updated with the new publisher"
-
8/7/2019 TRUNCATE TABLE
11/25
RETURN(0)ENDGO
ISNULL
SQL Server 2000
Replaces NULL with the specified replacement value.
Syntax
ISNULL ( check_expression ,replacement_value )
Arguments
check_expression
Is the expression to be checked for NULL. check_expression can be of any type.
replacement_value
Is the expression to be returned ifcheck_expression is NULL. replacement_value must have thesame type as check_expresssion.
Return Types
Returns the same type as check_expression.
-
8/7/2019 TRUNCATE TABLE
12/25
Remarks
The value ofcheck_expression is returned if it is not NULL; otherwise, replacement_value isreturned.
Examples
A. Use ISNULL with AVG
This example finds the average of the prices of all titles, substituting the value $10.00 for allNULL entries in the price column of the titles table.
USE pubsGOSELECT AVG(ISNULL(price, $10.00))FROM titlesGO
Here is the result set:
--------------------------14.24
(1 row(s) affected)
B. Use ISNULL
This example selects the title, type, and price for all books in the titles table. If the price for agiven title is NULL, the price shown in the result set is 0.00.
USE pubsGOSELECT SUBSTRING(title, 1, 15) AS Title, type AS Type,
ISNULL(price, 0.00) AS PriceFROM titlesGO
Here is the result set:
Title Type Price--------------- ------------ --------------------------The Busy Execut business 19.99
Cooking with Co business 11.95You Can Combat business 2.99Straight Talk A business 19.99Silicon Valley mod_cook 19.99The Gourmet Mic mod_cook 2.99The Psychology UNDECIDED 0.00But Is It User popular_comp 22.95Secrets of Sili popular_comp 20.00Net Etiquette popular_comp 0.00Computer Phobic psychology 21.59
-
8/7/2019 TRUNCATE TABLE
13/25
Is Anger the En psychology 10.95Life Without Fe psychology 7.00Prolonged Data psychology 19.99Emotional Secur psychology 7.99Onions, Leeks, trad_cook 20.95Fifty Years in trad_cook 11.95Sushi, Anyone? trad_cook 14.99
(18 row(s) affected)
SET @local_variable
SQL Server 2000
Sets the specified local variable, previously created with the DECLARE @local_variablestatement, to the given value.
Syntax
SET { { @local_variable=expression }
| { @cursor_variable= { @cursor_variable | cursor_name| { CURSOR [ FORWARD_ONLY | SCROLL ]
[ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ][ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ][ TYPE_WARNING ]
FORselect_statement[ FOR { READ ONLY | UPDATE [ OF column_name [ ,...n ] ] }]
}} }
}
Arguments
@local_variable
Is the name of a variable of any type except cursor, text, ntext, orimage. Variable names mustbegin with one at sign (@). Variable names must conform to the rules for identifiers. For moreinformation, see Using Identifiers.
http://msdn.microsoft.com/en-us/library/aa223962(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa223962(v=SQL.80).aspx -
8/7/2019 TRUNCATE TABLE
14/25
expression
Is any valid Microsoft SQL Server expression.
cursor_variable
Is the name of a cursor variable. If the target cursor variable previously referenced a differentcursor, that previous reference is removed.
cursor_name
Is the name of a cursor declared using the DECLARE CURSOR statement.
CURSOR
Specifies that the SET statement contains a declaration of a cursor.
SCROLL
Specifies that the cursor supports all fetch options (FIRST, LAST, NEXT, PRIOR, RELATIVE,and ABSOLUTE). SCROLL cannot be specified if FAST_FORWARD is also specified.
FORWARD_ONLY
Specifies that the cursor supports only the FETCH NEXT option. The cursor can be retrievedonly in one direction, from the first to the last row. If FORWARD_ONLY is specified withoutthe STATIC, KEYSET, or DYNAMIC keywords, the cursor is implemented as DYNAMIC.
When neither FORWARD_ONLY nor SCROLL is specified, FORWARD_ONLY is the default,unless the keywords STATIC, KEYSET, or DYNAMIC are specified. STATIC, KEYSET, andDYNAMIC cursors default to SCROLL. FAST_FORWARD and FORWARD_ONLY aremutually exclusive; if one is specified the other cannot be specified.
STATIC
Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests tothe cursor are answered from this temporary table in tempdb; therefore, modifications made tobase tables are not reflected in the data returned by fetches made to this cursor, and this cursordoes not allow modifications.
KEYSET
Specifies that the membership and order of rows in the cursor are fixed when the cursor isopened. The set of keys that uniquely identify the rows is built into a table in tempdb known asthe keyset. Changes to nonkey values in the base tables, either made by the cursor owner orcommitted by other users, are visible as the owner scrolls around the cursor. Inserts made byother users are not visible (inserts cannot be made through a Transact-SQL server cursor). If a
-
8/7/2019 TRUNCATE TABLE
15/25
row is deleted, an attempt to fetch the row returns an @@FETCH_STATUS of -2. Updates ofkey values from outside the cursor resemble a delete of the old row followed by an insert of thenew row. The row with the new values is not visible, and attempts to fetch the row with the oldvalues return an @@FETCH_STATUS of -2. The new values are visible if the update is donethrough the cursor by specifying the WHERE CURRENT OF clause.
DYNAMIC
Defines a cursor that reflects all data changes made to the rows in its result set as you scrollaround the cursor. The data values, order, and membership of the rows can change on each fetch.The absolute and relative fetch options are not supported with dynamic cursors.
FAST_FORWARD
Specifies a FORWARD_ONLY, READ_ONLY cursor with optimizations enabled.FAST_FORWARD cannot be specified if SCROLL is also specified. FAST_FORWARD and
FORWARD_ONLY are mutually exclusive, if one is specified the other cannot be specified.
READ_ONLY
Prevents updates from being made through this cursor. The cursor cannot be referenced in aWHERE CURRENT OF clause in an UPDATE or DELETE statement. This option overrides thedefault capability of a cursor to be updated.
SCROLL LOCKS
Specifies that positioned updates or deletes made through the cursor are guaranteed to succeed.
SQL Server locks the rows as they are read into the cursor to ensure their availability for latermodifications. SCROLL_LOCKS cannot be specified if FAST_FORWARD is also specified.
OPTIMISTIC
Specifies that positioned updates or deletes made through the cursor do not succeed if the rowhas been updated since it was read into the cursor. SQL Server does not lock rows as they areread into the cursor. It instead uses comparisons oftimestamp column values, or a checksumvalue if the table has no timestamp column, to determine if the row was modified after it wasread into the cursor. If the row was modified, the attempted positioned update or delete fails.OPTIMISTIC cannot be specified if FAST_FORWARD is also specified.
TYPE_WARNING
Specifies that a warning message is sent to the client if the cursor is implicitly converted fromthe requested type to another.
FORselect_statement
-
8/7/2019 TRUNCATE TABLE
16/25
Is a standard SELECT statement that defines the result set of the cursor. The keywordsCOMPUTE, COMPUTE BY, FOR BROWSE, and INTO are not allowed within theselect_statementof a cursor declaration.
If DISTINCT, UNION, GROUP BY, or HAVING are used, or an aggregate expression is
included in theselect_list, the cursor will be created as STATIC.
If each of the underlying tables does not have a unique index and an SQL-92 SCROLL cursor ora Transact-SQL KEYSET cursor is requested, it will automatically be a STATIC cursor.
Ifselect_statementcontains an ORDER BY in which the columns are not unique row identifiers,a DYNAMIC cursor is converted to a KEYSET cursor, or to a STATIC cursor if a KEYSETcursor cannot be opened. This also happens for a cursor defined using SQL-92 syntax butwithout the STATIC keyword.
READ ONLY
Prevents updates from being made through this cursor. The cursor cannot be referenced in aWHERE CURRENT OF clause in an UPDATE or DELETE statement. This option overrides thedefault capability of a cursor to be updated. This keyword varies from the earlier READ_ONLYby having a space instead of an underscore between READ and ONLY.
UPDATE [OF column_name [,...n]]
Defines updatable columns within the cursor. If OF column_name [,...n] is supplied, only thecolumns listed will allow modifications. If no list is supplied, all columns can be updated, unlessthe cursor has been defined as READ_ONLY.
Remarks
After declaration, all variables are initialized to NULL. Use the SET statement to assign a valuethat is not NULL to a declared variable. The SET statement that assigns a value to the variablereturns a single value. When initializing multiple variables use a separate SET statement for eachlocal variable.
Variables can be used only in expressions, not in place of object names or keywords. Toconstruct dynamic SQL statements, use EXECUTE.
The syntax rules for SET @cursor_variable do not include the LOCAL and GLOBALkeywords. When the SET @cursor_variable = CURSOR... syntax is used, the cursor is createdas GLOBAL or LOCAL, depending on the setting of the default to local cursor databaseoption.
Cursor variables are always local, even if they reference a global cursor. When a cursor variablereferences a global cursor, the cursor has both a global and a local cursor reference. For moreinformation, see Example C.
-
8/7/2019 TRUNCATE TABLE
17/25
For more information, see DECLARE CURSOR.
Permissions
SET @local_variablepermissions default to all users.
Examples
A. Print the value of a variable initialized with SET
This example creates the @myvar variable, places a string value into the variable, and prints thevalue of the @myvar variable.
DECLARE @myvar char(20)SET @myvar = 'This is a test'SELECT @myvarGO
B. Use a local variable assigned a value with SET in a SELECT statement
This example creates a local variable named @state and uses this local variable in a SELECTstatement to find all author first and last names where the author resides in the state of Utah.
USE pubsGODECLARE @state char(2)SET @state = 'UT'SELECT RTRIM(au_fname) + ' ' + RTRIM(au_lname) AS Name, stateFROM authorsWHERE state = @state
GO
C. Use SET with a global cursor
This example creates a local variable and then sets the cursor variable to the global cursor name.
DECLARE my_cursor CURSOR GLOBAL FOR SELECT * FROM authorsDECLARE @my_variable CURSORSET @my_variable = my_cursor
/* There is a GLOBAL declaredreference (my_cursor) and a LOCAL variablereference (@my_variable) to the my_cursor
cursor. */DEALLOCATE my_cursor /* There is now only a LOCAL variablereference (@my_variable) to the my_cursorcursor. */
D. Define a cursor with SET
This example uses the SET statement to define a cursor.
http://msdn.microsoft.com/en-us/library/aa258831(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258831(v=SQL.80).aspx -
8/7/2019 TRUNCATE TABLE
18/25
DECLARE @CursorVar CURSOR
SET @CursorVar = CURSOR SCROLL DYNAMICFORSELECT LastName, FirstNameFROM Northwind.dbo.EmployeesWHERE LastName like 'B%'
OPEN @CursorVar
FETCH NEXT FROM @CursorVarWHILE @@FETCH_STATUS = 0BEGIN
FETCH NEXT FROM @CursorVarEND
CLOSE @CursorVarDEALLOCATE @CursorVar
E. Assign a value from a query
This example uses a query to assign a value to a variable.
USE NorthwindGODECLARE @rows intSET @rows = (SELECT COUNT(*) FROM Customers)
EXECUTE
SQL Server 2000
Topic last updated -- July 2003
Executes a scalar-valued, user-defined function, a system procedure, a user-defined storedprocedure, or an extended stored procedure. Also supports the execution of a character stringwithin a Transact-SQL batch.
-
8/7/2019 TRUNCATE TABLE
19/25
Security Note Validate all user input. Do not concatenate user input before validating it. Neverexecute a command constructed from unvalidated user input. For more information, seeValidating User Input.
To invoke a function, use the syntax described for EXECUTE stored_procedure.
Syntax
Execute a stored procedure:
[ [ EXEC [ UTE ] ]{
[ @return_status= ]{procedure_name [ ;number] | @procedure_name_var
}[ [ @parameter= ] { value | @variable [ OUTPUT ] | [ DEFAULT ] ]
[ ,...n ][ WITH RECOMPILE ]
Execute a character string:
EXEC [ UTE ] ( { @string_variable | [ N ] 'tsql_string' } [ + ...n ] )
Arguments
@return_status
Is an optional integer variable that stores the return status of a stored procedure. This variablemust be declared in the batch, stored procedure, or function before it is used in an EXECUTEstatement.
When used to invoke a scalar-valued user-defined function, the @return_status variable can beof any scalar data type.
procedure_name
Is the fully qualified or nonfully qualified name of the stored procedure to call. Procedure namesmust conform to the rules for identifiers. For more information, see Using Identifiers. The namesof extended stored procedures are always case-sensitive, regardless of the code page or sort order
of the server.
A procedure that has been created in another database can be executed if the user executing theprocedure owns the procedure or has the appropriate permission to execute it in that database. Aprocedure can be executed on another server running Microsoft SQL Server if the userexecuting the procedure has the appropriate permission to use that server (remote access) and toexecute the procedure in that database. If a server name is specified but no database name isspecified, SQL Server looks for the procedure in the user's default database.
http://msdn.microsoft.com/en-us/library/aa174437(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa223962(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa223962(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa174437(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa223962(v=SQL.80).aspx -
8/7/2019 TRUNCATE TABLE
20/25
;number
Is an optional integer used to group procedures of the same name so they can be dropped with asingle DROP PROCEDURE statement. This parameter is not used for extended storedprocedures.
Procedures used in the same application are often grouped this way. For example, the proceduresused with the orders application may be named orderproc;1, orderproc;2, and so on. Thestatement DROP PROCEDURE orderproc drops the entire group. After the procedures havebeen grouped, individual procedures within the group cannot be dropped. For example, thestatement DROP PROCEDURE orderproc;2 is not allowed. For more information aboutprocedure groups, see CREATE PROCEDURE.
@procedure_name_var
Is the name of a locally defined variable that represents a stored procedure name.
@parameter
Is the parameter for a procedure, as defined in the CREATE PROCEDURE statement. Parameternames must be preceded by the at sign (@). When used with the @parameter_name=value form,parameter names and constants do not have to be supplied in the order in which they are definedin the CREATE PROCEDURE statement. However, if the @parameter_name=value form isused for any parameter, it must be used for all subsequent parameters.
Parameters are nullable by default. If a NULL parameter value is passed and that parameter isused in a CREATE or ALTER TABLE statement in which the column referenced does not allow
NULLs (for example, inserting into a column that does not allow NULLs), SQL Server generatesan error. To prevent passing a parameter value of NULL to a column that does not allow NULLs,either add programming logic to the procedure or use a default value (with the DEFAULTkeyword of CREATE or ALTER TABLE) for the column.
value
Is the value of the parameter to the procedure. If parameter names are not specified, parametervalues must be supplied in the order defined in the CREATE PROCEDURE statement.
If the value of a parameter is an object name, character string, or qualified by a database name or
owner name, the entire name must be enclosed in single quotation marks. If the value of aparameter is a keyword, the keyword must be enclosed in double quotation marks.
If a default is defined in the CREATE PROCEDURE statement, a user can execute the procedurewithout specifying a parameter. The default must be a constant and can include the wildcardcharacters %, _, [ ], and [^] if the procedure uses the parameter name with the LIKE keyword.
http://msdn.microsoft.com/en-us/library/aa258259(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258259(v=SQL.80).aspx -
8/7/2019 TRUNCATE TABLE
21/25
The default can also be NULL. Usually, the procedure definition specifies the action that shouldbe taken if a parameter value is NULL.
@variable
Is the variable that stores a parameter or a return parameter.
OUTPUT
Specifies that the stored procedure returns a parameter. The matching parameter in the storedprocedure must also have been created with the keyword OUTPUT. Use this keyword whenusing cursor variables as parameters.
If OUTPUT parameters are being used and the intent is to use the return values in otherstatements within the calling batch or procedure, the value of the parameter must be passed as avariable (that is, @parameter= @variable). You cannot execute a procedure specifying
OUTPUT for a parameter that is not defined as an OUTPUT parameter in the CREATEPROCEDURE statement. Constants cannot be passed to stored procedures using OUTPUT; thereturn parameter requires a variable name. The variable's data type must be declared and a valueassigned before executing the procedure. Return parameters can be of any data type except thetext orimage data types.
DEFAULT
Supplies the default value of the parameter as defined in the procedure. When the procedureexpects a value for a parameter that does not have a defined default and either a parameter ismissing or the DEFAULT keyword is specified, an error occurs.
n
Is a placeholder indicating that the preceding item(s) can be repeated multiple times. Forexample, EXECUTE can specify one or more @parameter, value, or @variable items.
WITH RECOMPILE
Forces a new plan to be compiled. Use this option if the parameter you are supplying is atypicalor if the data has significantly changed. The changed plan is used in subsequent executions. Thisoption is not used for extended stored procedures. It is recommended that you use this option
sparingly because it is expensive.
@string_variable
Is the name of a local variable. @string_variable can be ofchar, varchar, nchar, ornvarchardata type with a maximum value of the server's available memory. You can use up to 4,000characters fornchar ornvarchar and 8,000 characters forchar orvarchar data type strings. Ifthe string is greater than 4,000 characters, concatenate multiple local variables to use for the
-
8/7/2019 TRUNCATE TABLE
22/25
EXECUTE string. For optimum performance, do not use more than 4,000 characters. For moreinformation about system-supplied SQL Server data types, see Data Types.
[N]'tsql_string'
Is a constant string. tsql_stringcan be ofnvarchar orvarchar data type. If the N is included, thestring is interpreted as nvarchar data type with a maximum value of the server's availablememory. If the string is greater than 4,000 characters, concatenate multiple local variables to usefor the EXECUTE string.
Remarks
If the first three characters of the procedure name are sp_, SQL Server searches the masterdatabase for the procedure. If no qualified procedure name is provided, SQL Server searches forthe procedure as if the owner name is dbo. To resolve the stored procedure name as a user-defined stored procedure with the same name as a system stored procedure, provide the fullyqualified procedure name.
Parameters can be supplied either by using value or by using @parameter_name = value. Aparameter is not part of a transaction; therefore, if a parameter is changed in a transaction that islater rolled back, the parameter's value does not revert to its previous value. The value returnedto the caller is always the value at the time the procedure returns.
Nesting occurs when one stored procedure calls another. The nesting level is incremented whenthe called procedure begins execution, and it is decremented when the called procedure hasfinished. Exceeding the maximum of 32 nesting levels causes the entire calling procedure chainto fail. The current nesting level is stored in the @@NESTLEVEL function.
Because remote stored procedures and extended stored procedures are not within the scope of atransaction (unless issued within a BEGIN DISTRIBUTED TRANSACTION statement or whenused with various configuration options), commands executed through calls to them cannot berolled back. For more information, see System Stored Procedures and BEGIN DISTRIBUTEDTRANSACTION.
When using cursor variables, if you execute a procedure that passes in a cursor variable with acursor allocated to it an error occurs.
You do not have to specify the EXECUTE keyword when executing stored procedures if thestatement is the first one in a batch.
Using EXECUTE with a Character String
Use the string concatenation operator (+) to create large strings for dynamic execution. Eachstring expression can be a mixture of Unicode and non-Unicode data types.
http://msdn.microsoft.com/en-us/library/aa258271(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa259564(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225991(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225991(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258271(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa259564(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225991(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225991(v=SQL.80).aspx -
8/7/2019 TRUNCATE TABLE
23/25
Although each [N] 'tsql_string' or@string_variable must be less than 8,000 bytes, theconcatenation is performed logically in the SQL Server parser and never materializes in memory.For example, this statement never produces the expected 16,000 concatenated character string:
EXEC('name_of_8000_char_string' + 'another_name_of_8000_char_string')
Statement(s) inside the EXECUTE statement are not compiled until the EXECUTE statement isexecuted.
Changes in database context last only until the end of the EXECUTE statement. For example,after the EXEC in this example, the database context is master:
USE master EXEC ("USE pubs") SELECT * FROM authors
Permissions
EXECUTE permissions for a stored procedure default to the owner of the stored procedure, who
can transfer them to other users. Permissions to use the statement(s) within the EXECUTE stringare checked at the time EXECUTE is encountered, even if the EXECUTE statement is includedwithin a stored procedure. When a stored procedure is run that executes a string, permissions arechecked in the context of the user who executes the procedure, not in the context of the user whocreated the procedure. However, if a user owns two stored procedures in which the firstprocedure calls the second, then EXECUTE permission checking is not performed for the secondstored procedure.
Examples
A. Use EXECUTE to pass a single parameter
The showind stored procedure expects one parameter (@tabname), a table name. The followingexamples execute the showind stored procedure with titles as its parameter value.
Note The showind stored procedure is shown for illustrative purposes only and does not exist inthe pubs database.
EXEC showind titles
The variable can be explicitly named in the execution:
EXEC showind @tabname = titles
If this is the first statement in a batch or an isql script, EXEC is not required:
showind titles
-Or-
showind @tabname = titles
-
8/7/2019 TRUNCATE TABLE
24/25
B. Use multiple parameters and an output parameter
This example executes the roy_checkstored procedure, which passes three parameters. The thirdparameter,@pc, is an OUTPUT parameter. After the procedure has been executed, the returnvalue is available in the variable @percent.
Note The roy_checkstored procedure is shown for illustrative purposes only and does not existin the pubs database.
DECLARE @percent intEXECUTE roy_check 'BU1032', 1050, @pc = @percent OUTPUTSET Percent = @percent
C. Use EXECUTE 'tsql_string' with a variable
This example shows how EXECUTE handles dynamically built strings containing variables.This example creates the tables_cursor cursor to hold a list of all user-defined tables (type= U).
Note This example is shown for illustrative purposes only.
DECLARE tables_cursor CURSORFORSELECT name FROM sysobjects WHERE type = 'U'
OPEN tables_cursorDECLARE @tablename sysnameFETCH NEXT FROM tables_cursor INTO @tablenameWHILE (@@FETCH_STATUS -1)BEGIN
/* A @@FETCH_STATUS of -2 means that the row has been deleted.There is no need to test for this because this loop drops all
user-defined tables. */.EXEC ('DROP TABLE ' + @tablename)FETCH NEXT FROM tables_cursor INTO @tablename
ENDPRINT 'All user-defined tables have been dropped from the database.'DEALLOCATE tables_cursor
D. Use EXECUTE with a remote stored procedure
This example executes the checkcontract stored procedure on the remote serverSQLSERVER1 and stores the return status indicating success or failure in @retstat.
DECLARE @retstat intEXECUTE @retstat = SQLSERVER1.pubs.dbo.checkcontract '409-56-4008'
E. Use EXECUTE with an extended stored procedure
This example uses the xp_cmdshell extended stored procedure to list a directory of all files withan .exe file name extension.
USE master
-
8/7/2019 TRUNCATE TABLE
25/25
EXECUTE xp_cmdshell 'dir *.exe'
F. Use EXECUTE with a stored procedure variable
This example creates a variable that represents a stored procedure name.
DECLARE @proc_name varchar(30)SET @proc_name = 'sp_who'EXEC @proc_name
G. Use EXECUTE with DEFAULT
This example creates a stored procedure with default values for the first and third parameters.When the procedure is run, these defaults are inserted for the first and third parameters if novalue is passed in the call or if the default is specified. Note the various ways the DEFAULTkeyword can be used.
USE pubs
IF EXISTS (SELECT name FROM sysobjectsWHERE name = 'proc_calculate_taxes' AND type = 'P')
DROP PROCEDURE proc_calculate_taxesGO-- Create the stored procedure.CREATE PROCEDURE proc_calculate_taxes (@p1 smallint = 42, @p2 char(1),
@p3 varchar(8) = 'CAR')AS
SELECT *FROM mytable
The proc_calculate_taxes stored procedure can be executed in many combinations:
EXECUTE proc_calculate_taxes @p2 = 'A'EXECUTE proc_calculate_taxes 69, 'B'EXECUTE proc_calculate_taxes 69, 'C', 'House'EXECUTE proc_calculate_taxes @p1 = DEFAULT, @p2 = 'D'EXECUTE proc_calculate_taxes DEFAULT, @p3 = 'Local', @p2 = 'E'EXECUTE proc_calculate_taxes 69, 'F', @p3 = DEFAULTEXECUTE proc_calculate_taxes 95, 'G', DEFAULTEXECUTE proc_calculate_taxes DEFAULT, 'H', DEFAULTEXECUTE proc_calculate_taxes DEFAULT, 'I', @p3 = DEFAULT