EXEC

The EXEC command (short for EXECUTE) has two uses: one is to execute a stored procedure, and the other is to execute a dynamic batch. The latter gets a character string within parentheses as an input and invokes the code within that character string. In the following section, I’ll describe EXEC(<string>) and some interesting enhancements introduced in SQL Server 2005 that increase its functionality.

A Simple EXEC Example

As a simple example of using EXEC, the following code returns the count of rows from a given variable table name:

SET NOCOUNT ON; USE Northwind; DECLARE @schemaname AS NVARCHAR(128), @tablename AS NVARCHAR(128); SET @schemaname = N'dbo'; SET @tablename = N'Orders'; DECLARE @objectname AS NVARCHAR(517); SET @objectname = QUOTENAME(@schemaname) ...

Get Inside Microsoft® SQL Server™ 2005 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.