我有一个简单的存储过程,如下所示:
IF EXISTS (SELECT tag, campaignID as campaignID
FROM Tags_Campaign_Watchlist
WHERE tag IN (SELECT *
FROM dbo.splitstring (@tags)))
这将返回:
的输出
我的目标是在此声明中,在表中找到的任何匹配项中,将广告系列ID插入另一个名为TableB的表中,只是不确定如何在检查其循环的字符串中的每个标记期间发生这种情况。
修改
在我执行插入的语句的底部,我需要从第一个插入顶部传递@lastID。这可能吗?
如果我通过@tags ='house,car,truck和最后一个插入1,2,3,它将添加house的campaignID和1,然后是car的campaignID和2的ID。
AS
BEGIN
SET NOCOUNT ON;
BEGIN
INSERT INTO Tags_Accounts (data, dataType, dataLocation, tag, whoAdded, whenAdded)
SELECT @dbData,
@dbDataType,
@location,
Name,
@ntid,
GETDATE()
FROM dbo.splitstring (@tags);
DECLARE @lastID int
SET @lastID = SCOPE_IDENTITY()
END
END
--If one of the tags added is part of a campaign watchlist, add it to the watchlist data table.
IF EXISTS (SELECT tag, campaignID as campaignID
FROM Tags_Campaign_Watchlist
WHERE tag IN (SELECT *
FROM dbo.splitstring (@tags)))
BEGIN
INSERT INTO Tags_Campaign_Watchlist_Data (campaignID, tagID)
SELECT campaignID
FROM Tags_Campaign_Watchlist
WHERE tag IN (SELECT *
FROM dbo.splitstring (@tags))
END
更新2
DECLARE @tags VARCHAR(MAX)
DECLARE @lastID int
SET @tags = 'bob,cat,carl,withdraw,awesome';
SET @lastID = '1';
BEGIN
IF EXISTS (SELECT tag, campaignID as campaignID
FROM Tags_Campaign_Watchlist
WHERE tag IN (SELECT *
FROM dbo.splitstring (@tags)))
INSERT INTO Tags_Campaign_Watchlist_Data (campaignID, tagID)
(SELECT campaignID, @lastID
FROM Tags_Campaign_Watchlist
WHERE tag IN (SELECT *
FROM dbo.splitstring (@tags)))
END
返回
Msg 515,Level 16,State 2,Line 14 无法将值NULL插入列'tag',表'local.dbo.Tags_Campaign_Watchlist_Data';列不允许空值。 INSERT失败。 声明已经终止。
我在监视列表数据中没有列TAG,jsut tagid和campaignID
答案 0 :(得分:1)
INSERT INTO TableB (campaignID)
SELECT campaignID
FROM Tags_Campaign_Watchlist
WHERE tag IN (SELECT *
FROM dbo.splitstring (@tags))
更新以进行修改
--If one of the tags added is part of a campaign watchlist, add it to the watchlist data table.
IF EXISTS (SELECT *
FROM Tags_Campaign_Watchlist
WHERE tag IN (SELECT *
FROM dbo.splitstring (@tags)))
BEGIN
INSERT INTO Tags_Campaign_Watchlist_Data (campaignID, tagID)
SELECT campaignID, TagID
FROM Tags_Campaign_Watchlist
WHERE tag IN (SELECT *
FROM dbo.splitstring (@tags))
END