gpt4 book ai didi

SQL 服务器 : Update table row using merge

转载 作者:行者123 更新时间:2023-12-04 13:38:21 25 4
gpt4 key购买 nike

你好,我正在尝试从动态变量更新表,但我总是得到不正确的语法,你能帮我看看我哪里出错了吗?

这是我运行查询时的消息。

select convert(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'.

ERROR: Incorrect syntax near '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 字符串来减少代码,但如果需要该信息,我可以随时添加它。

最佳答案

  1. 在变量替换后的实际动态 SQL 中,您使用 targetsource 保留字作为表别名。使用方括号 [target] 或更好的方法是像在“整个查询”代码示例中那样使用 T
  2. T.stat = S.stat 后动态 SQL 中缺少逗号。

关于SQL 服务器 : Update table row using merge,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36260963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com