[英]select into a table using a variable as table name dynamic sql not working
[英]Table variable not working in dynamic SQL
我的觸發器如下
Alter TRIGGER [dbo].[LogTable_InsertTrigger] on [dbo].[std_table] AFTER INSERT
as
DECLARE @ColName varchar(50), @QueryText nvarchar(max)
declare @inserted TABLE(
[CountryID] [int] NOT NULL,
[Country] [nvarchar](255) NOT NULL,
[RegionId] [int] NULL
)
insert into @inserted
select * from inserted
DECLARE objCursor CURSOR FAST_FORWARD FOR
select ColName from dbo.getColumnNames('std_table')
OPEN objCursor
FETCH NEXT FROM objCursor INTO @ColName
WHILE @@FETCH_STATUS = 0
BEGIN
set @QueryText= '
insert into dbo.LogTable
(StandardType,Attribute,Action,NEwValue,UserId,ModifiedDate)
select ''Country'','''+@ColName+''',''Insert'','+@ColName+',1,getdate()
from @inserted'
EXEC sp_executesql @QueryText
FETCH NEXT FROM objCursor INTO @ColName
END
CLOSE objCursor
DEALLOCATE objCursor
當我嘗試插入DA層中的表std_table時,出現異常Must declare the table variable "@inserted"
。
我不能直接使用插入的表,因為我正在編寫一個動態查詢,在該查詢中魔術表將無法工作。 因此,我試圖將插入表中的數據轉儲到臨時表中並從中進行訪問。
我嘗試過
select *
into #inserted
from inserted
這可行,但是由於許多用戶都通過網絡訪問了我的應用程序,因此將導致數據問題。 所以我不能用這個。
這里有幾處錯誤。
CountryID,Country,RegionID
嗎? 如果您確實需要動態地執行此操作,那么似乎可以在沒有顯式游標的情況下以更簡單的方式執行此操作-並不是說這一定是一件壞事,否則它的性能將比下面的要差,但是游標的功能更多詳細和丑陋的代碼:
ALTER TRIGGER [dbo].[LogTable_InsertTrigger]
ON [dbo].[std_table]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
SELECT * INTO #t FROM inserted;
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'';
SELECT @sql = @sql + CHAR(13) + CHAR(10) + N'INSERT INTO dbo.LogTable
(StandardType,Attribute,Action,NewValue,UserId,ModifiedDate)
SELECT ''Country'','''+ColName+''',''Insert'','+ColName+',1,GETDATE()
FROM #t;'
FROM dbo.GetColumnNames('std_table');
EXEC sp_executesql @sql;
END
GO
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.