2016-08-02 27 views
1
EXEC('INSERT INTO T_MyTable('+ @Columns +') 
     EXEC ('+ @UpdateString + ')' 
     ) 

凡@columns包含逗號分隔的列名和@UpdateString包含無法使用EXEC

'Update T_OtherTable 
Set col1 = 123, 
col2 = 456, 
col3 = 'nice' 
OUTPUT 
DELETED.col1 as Old_FirstCol 
INSERTED.col1 as New_FirstCol 
DELETED.col2 as Old_SecondCol 
INSERTED.col2 as New_SecondCol 
DELETED.col3 as Old_ThridCol 
INSERTED.col3 as New_ThirdCol 
Where ID = 1' 

我得到不正確的語法錯誤插入到表中。我們不能在EXEC內部使用EXEC嗎?

回答

2

你缺少輸出列名之後逗號,

'Update T_OtherTable 
Set col1 = 123, 
col2 = 456, 
col3 = ''nice'' 
OUTPUT 
DELETED.col1 as Old_FirstCol, 
INSERTED.col1 as New_FirstCol, 
DELETED.col2 as Old_SecondCol, 
INSERTED.col2 as New_SecondCol, 
DELETED.col3 as Old_ThridCol, 
INSERTED.col3 as New_ThirdCol 
Where ID = 1' 

而且它能夠更好地直接從OUTPUT子句然後使用嵌套EXEC插入數據表。它應該是這樣的,

'Update T_OtherTable 
Set col1 = 123, 
col2 = 456, 
col3 = ''nice'' 
OUTPUT 
DELETED.col1 as Old_FirstCol, 
INSERTED.col1 as New_FirstCol, 
DELETED.col2 as Old_SecondCol, 
INSERTED.col2 as New_SecondCol, 
DELETED.col3 as Old_ThridCol, 
INSERTED.col3 as New_ThirdCol 
INTO T_MyTable('+ @Columns +') 
Where ID = 1' 
+1

謝謝您@Jatin第二個方法讓我的代碼更簡單 –

4

你應該逃避的報價爲雙引號,看看這個簡單的查詢:

DECLARE @sql varchar(20) = 'SELECT 1'; 
EXEC ('EXEC('''[email protected]+''')') 
+0

感謝@Pawel DYL –

2

我認爲問題出在近nice報價。它應該是:

'Update T_OtherTable 
Set col1 = 123, 
col2 = 456, 
col3 = ''nice'' 
OUTPUT 
DELETED.col1 as Old_FirstCol 
INSERTED.col1 as New_FirstCol 
DELETED.col2 as Old_SecondCol 
INSERTED.col2 as New_SecondCol 
DELETED.col3 as Old_ThridCol 
INSERTED.col3 as New_ThirdCol 
Where ID = 1' 
1

把足夠的報價爲@UpdateString:

DECLARE @UpdateString VARCHAR(max) = '''SELECT ''''text'''',1'''; 
EXEC ('EXEC('[email protected]+')')