SQL 中要根据结果添加或更新的逗号分隔 ID 列表
List of comma separated IDs in SQL to add or update based on result
我从 table 中检索了一个逗号分隔的项目列表,结果是这样
declare @IDs = varchar(max)
set @IDs = '11,23,33,44,55' -- this varies
从现在开始,我想做的是遍历每一个并与我的 table 进行比较,看看该 ID 是否存在,如果存在,则更新该行,但如果它不添加一行我的 table.
感谢任何帮助。
你需要这样的东西(MERGE
):
MERGE targetTableName AS TARGET
USING @tableOfIds AS SOURCE
ON ( TARGET.Id = SOURCE.Id )
WHEN MATCHED THEN
UPDATE
-- Here you will put your update statement. I mean SET...
其中 @tableOfIds
是一个 table 将保存您的 ID,一个 table 只有一列,我们称它为 Id
.
我从 table 中检索了一个逗号分隔的项目列表,结果是这样
declare @IDs = varchar(max)
set @IDs = '11,23,33,44,55' -- this varies
从现在开始,我想做的是遍历每一个并与我的 table 进行比较,看看该 ID 是否存在,如果存在,则更新该行,但如果它不添加一行我的 table.
感谢任何帮助。
你需要这样的东西(MERGE
):
MERGE targetTableName AS TARGET
USING @tableOfIds AS SOURCE
ON ( TARGET.Id = SOURCE.Id )
WHEN MATCHED THEN
UPDATE
-- Here you will put your update statement. I mean SET...
其中 @tableOfIds
是一个 table 将保存您的 ID,一个 table 只有一列,我们称它为 Id
.