Bạn sẽ sử dụng sp_executesql
. Các biến bị ràng buộc trông giống như sau: @var1
.
Từ liên kết dưới đây, một truy vấn Ví dụ đối với các cơ sở dữ liệu Northwind tiêu chuẩn:
DECLARE @IntVariable int;
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
/* Build the SQL string one time.*/
SET @SQLString =
N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
FROM AdventureWorks2008R2.HumanResources.Employee
WHERE BusinessEntityID = @BusinessEntityID';
SET @ParmDefinition = N'@BusinessEntityID tinyint';
/* Execute the string with the first parameter value. */
SET @IntVariable = 197;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@BusinessEntityID = @IntVariable;
/* Execute the same string with the second parameter value. */
SET @IntVariable = 109;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@BusinessEntityID = @IntVariable;
Chi tiết đầy đủ và cú pháp ví dụ là tại các liên kết sau đây:
http://msdn.microsoft.com/en-us/library/ms188001.aspx
http://msdn.microsoft.com/en-us/library/ms175170.aspx
Ồ, tôi biết SQL động là một cơn ác mộng! Nhưng... – briantyler