我正在使用Table-Valued Parameter来使用以下代码构建dyNamic查询
AlTER PROCEDURE [dbo].[ABC]
@tblName Varchar(1000),
@Details ABC_TYPE Readonly
AS
BEGIN
Declare @PK as nvarchar(1000)
Declare @SyncFlag as nvarchar(1) ='S'
Declare @SelectCommand as nvarchar(1200)
Declare @tblName2 as nvarchar(1000) ='@Details_N'
Set @PK = 'PK'
Declare @Details_N as table (Pk int)
Insert into @Details_N(Pk)
select PK from @Details
set @SelectCommand = 'Update A ' + ' set A.Sync_Flag ='''+ @SyncFlag + ''' From '+ @tblName + ' A, ' + @tblName2 + ' B ' +
' where A.' + @PK +'='+ 'B.PK'
EXEC sp_executesql @SelectCommand;
这给了我错误
必须声明表变量“@Details_N”
找不到我的错误
答案 0 :(得分:1)
表变量的范围是针对特定批处理(相同的上下文),而临时表是针对SPID的。 EXEC命令在不同的上下文中运行。改为使用临时表:
Declare @tblName2 as nvarchar(1000) ='#Details_N'
CREATE TABLE #Details_N (Pk int)
Insert into #Details_N(Pk)
select PK from @Details
答案 1 :(得分:1)
在动态查询内部,您不能使用外部声明的表变量。请改用临时表。你也有点复杂,这里是一个更清洁的版本
String query_coinDetailTable = "CREATE TABLE " + COIN_DETAILS_TABLE + "("+ UID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ CAP_24HR_CAHNGE + " TEXT," + LONG + " TEXT," + MK_CAP + " TEXT," + PERC + " TEXT," + PRICE + " TEXT,"
+ SHAPESHIFT + " TEXT," + SHORT + " TEXT," + SUPPLY + " TEXT," + USD_VOLUME + " TEXT," + VOLUME + " TEXT,"
+ VWAP_DATA + " TEXT," + VWAP_DATA_BTC + " TEXT," + FAB + " INTEGER DEFAULT 0" + ")";
开始使用DECLARE @SyncFlag AS NVARCHAR(1) ='S'
DECLARE @SelectCommand AS NVARCHAR(1200)
CREATE TABLE #Details_N(Pk INT)
INSERT INTO #Details_N(Pk)
SELECT PK
FROM @Details
SET @SelectCommand = 'Update A ' + ' set A.Sync_Flag = @SyncFlag
From '+ Quotename(@tblName) + ' A
inner join #Details_N B '+ 'on A.PK =' + 'B.PK'
EXEC Sp_executesql
@SelectCommand,
N'@SyncFlag NVARCHAR(1)',
@SyncFlag
语法,旧式逗号分隔连接已弃用