Assigning Variable Values from the Database

Assigning Variable Values from the Database

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 = @@servername
PRINT @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 Northwind
DECLARE @CustRowCount int
SET @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.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.