Assigning Variable Values from the Database
If you write T-SQL scripts that need to be portable between servers, you'll want to learn how to assign values that come from a SQL Server Express database to T-SQL variables.
December 16, 2007
When you've mastered manipulating variables using T-SQL code from stored procedures or T-SQL batches, you'll start finding ways you can leverage variables by assigning them values that come from a SQL Server Express database. For example, if you write T-SQL scripts that need to be portable between servers, you'll probably want to learn how to retrieve the server instance name and assign it to a variable. Here's how to use the @@servername built-in function to assign the SQL Server instance name to a T-SQL variable named @MyServerName:
DECLARE @MyServerName varchar(50)SET @MyServerName = @@servernamePRINT @MyServerName
Retrieving the row count returned by a query is another practical technique. In addition to being useful information for application users, the row count can help you to determine how to best display and navigate through a returned result set. Consider the example
USE NorthwindGODECLARE @CustRowCount intSET @CustRowCount = (SELECT COUNT(*) FROM Customers)PRINT @CustRowCount
This code declares an integer variable named @CustRowCount, then assigns that variable the total number of rows from the Customers table in the sample Northwind database.
About the Author
You May Also Like