create a dynamic sql statement and save it in a varchar type variable : Dynamic SQL « Transact SQL « SQL Server / T-SQL Tutorial






3> CREATE TABLE Employees (
4>      EmployeeID int NOT NULL ,
5>      LastName nvarchar (20) NOT NULL ,
6>      FirstName nvarchar (10) NOT NULL ,
7>      Title nvarchar (30) NULL ,
8>      TitleOfCourtesy nvarchar (25) NULL ,
9>      BirthDate datetime NULL ,
10>     HireDate datetime NULL ,
11>     Address nvarchar (60) NULL ,
12>     City nvarchar (15) NULL ,
13>     Region nvarchar (15) NULL ,
14>     PostalCode nvarchar (10) NULL ,
15>     Country nvarchar (15) NULL ,
16>     HomePhone nvarchar (24) NULL ,
17>     Extension nvarchar (4) NULL ,
18>     Photo image NULL ,
19>     Notes ntext NULL ,
20>     ReportsTo int NULL ,
21>     PhotoPath nvarchar (255) NULL
22>
23> )
24> GO
1>
2>
3>    DECLARE @InVar   varchar(200)
4>
5>    SET @InVar = 'DECLARE @OutVar varchar(50)
6~                 SELECT @OutVar = FirstName FROM Employees WHERE EmployeeID = 1
7~                 SELECT ''The Value Is '' + @OutVar'
8>
9>    EXEC (@Invar)
10>    GO

---------------------------------------------------------------
NULL

(1 rows affected)
1>
2>    drop table Employees;
3>    GO








20.18.Dynamic SQL
20.18.1.A stored procedure with dynamic execution.
20.18.2.Simple SELECT query that uses a variable for the field to sequence the result set.
20.18.3.SELECT query with a variable for the table name so that condition determines which table the result set is based on.
20.18.4.Using Stored Procedure to create dynamic sql statement
20.18.5.Change database dynamically
20.18.6.Pass parameters into dynamic sql statement
20.18.7.Build a dynamic sql statement from schema name, table name and column name
20.18.8.create a dynamic sql statement and save it in a varchar type variable