您好我正在尝试从动态变量更新表格,但我总是得到不正确的语法,你能帮助我在哪里犯了错误吗?
这是我运行查询时的消息。
选择转换(varchar(55),refdate)+' - '+ convert(varchar(55),refcount)FROM [gen_048_MAR2016]
MERGE gen_048_MAR2016 as target USING #temp1 as source ON target.refcount = source.refnum AND sourc3e.tsql = target.refcount WHEN MATCHED THEN UPDATE SET target.stat = source.stat target.statdate = source.statdate WHEN NOT MATCHED BY TARGET THEN INSERT (stat, statdate) VALUES (S.stat, S.statdate) ; Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'target'.
错误:'target'附近的语法不正确。
我没有写完整个查询,所以我只是复制并粘贴我认为我犯了错误的一方。
CREATE TABLE #records(
[index] int PRIMARY KEY IDENTITY
,refnum varchar(200)
,stat varchar(200)
,statdate varchar(200)
)
insert into #records (refnum, stat, statdate)
select
dbo.fn_Parsename(WHOLEROW,'|',0),
dbo.fn_Parsename(WHOLEROW,'|',3),
dbo.fn_Parsename(WHOLEROW,'|',4)
from #temp1
declare @refnum varchar(100)
declare @stat varchar(100)
declare @statdate varchar(100)
declare @sql NVARCHAR(MAX),
declare @index int
WHILE (@index <= (SELECT MAX([index]) FROM #records))
BEGIN
set @stat = (select stat from #records where [index] = @index)
select @stat
set @statdate = (select statdate from #records where [index] = @index)
select @statdate
set @refnum = (select refnum from #records where [index] = @index)
set @refnum = replace(@refnum, 'F', '')
select @refnum
set @sql = '
MERGE '+@sourceTable+' T
USING #temp1 S
ON T.refcount = S.refnum
AND S.tsql = T.refcount
WHEN MATCHED THEN
UPDATE
SET
T.stat = S.stat
T.statdate = S.statdate
WHEN NOT MATCHED BY TARGET THEN
INSERT (stat, statdate)
VALUES (S.stat, S.statdate)
;'
select @refnum, @stat, @statdate
print @sql
exec (@sql)
SELECT 'File has been successfully uploaded', @fileDate,'success' as msg
set @index = @index + 1
END
我没有使用@sourceTable
字符串来减少代码,但如果需要该信息,我可以随时添加它。
答案 0 :(得分:0)
target
和source
保留字作为表别名。使用方括号[target]
或更好的T
,就像在&#34;整个查询&#34;代码示例。T.stat = S.stat
之后,您在动态SQL中缺少逗号。