EXEC('INSERT INTO T_MyTable('+ @Columns +')
EXEC ('+ @UpdateString + ')'
)
其中@Columns包含逗号分隔的列名,而@UpdateString包含
'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吗?
答案 0 :(得分:4)
您应该将引号转义为双引号,请查看此简化查询:
DECLARE @sql varchar(20) = 'SELECT 1';
EXEC ('EXEC('''+@sql+''')')
答案 1 :(得分: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'
答案 2 :(得分:2)
OUTPUT中的列名后缺少逗号,
'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'
答案 3 :(得分:1)
将足够的引号放入@UpdateString:
DECLARE @UpdateString VARCHAR(max) = '''SELECT ''''text'''',1''';
EXEC ('EXEC('+@UpdateString+')')