Hello I am using trying to update a table from dynamic variable but I always got Incorrect syntax, can you help me where did I made a mistake?
This is the message when I run the query.
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'.
I didn't write the whole query so I just copy and paste the party where I think I made an error.
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
I didn't put the @sourceTable
string to lessen the codes, but I can add it anytime if that info is needed.
target
and source
reserved words as table aliases. Use square brackets [target]
or better still just T
as you do in "the whole query" code sample. T.stat = S.stat
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.