首页 > 解决方案 > 是否可以在使用局部变量的 Transact-SQL 查询中使用 SqlParameter?

问题描述

假设我有一个执行以下操作的事务 SQL 查询:

INSERT INTO Table1 -- Table1 has an identity column for the primary key
(
   Table1Value1,
   Table1Value2
)
VALUES
(
   @Table1Value1, -- SqlParameter
   @Table1Value2 -- SqlParameter
)   
DECLARE @table1ID int = SCOPE_IDENTITY();

INSERT INTO Table2 -- Table2 also has and identity column for the PK
(
   Table1ID -- Must have foreign key to Table1 record
   Table2Value1,
   Table2Value2
)
VALUES
(
    @table1ID,
    @Table2Value1, -- SqlParameter
    @Table2Value2  -- SqlParameter
)

DECLARE @table2ID int = SCOPE_IDENTITY();

INSERT INTO Table3
(
   Table1ID, -- Foreign Key to Table1 record
   Table2ID, -- Foreign Key to Table2 record
   Table3Value1,
   Table3Value2
)
VALUES
(
   @table1ID, -- Foreign Key to Table1 record
   @table2ID, -- Foreign Key to Table2 record
   @Table3Value1, -- SqlParameter
   @Table3Value2 -- SqlParameter
)

有没有办法使这项工作?您能否转义本地 transact-sql 变量名,以便无论找出参数的位置,它们都会被忽略吗?你能告诉 SqlClient 使用 @ 以外的东西来识别参数吗?有没有办法在不使用存储过程或不必运行子查询的情况下完成这项工作?

谢谢。

标签: sql-servertsqlsqlclientsqlparameter

解决方案


这一定是一个错字。我把它改回来了,现在它可以工作了。这里唯一的教训是不要在 48 小时内工作 40 小时,并且您可以将参数与 transact-sql 局部变量混合使用。:-)

我不会反对删除这个。


推荐阅读