TSQL追加到行

时间:2013-10-30 20:56:15

标签: sql-server tsql

我有一个包含帐号和标签(关键字)的表格。我的查询会检查该帐户是否存在,如果存在,则需要将新关键字附加到已退出的帐户。

如果帐户没有退出,则只需进行简单插入。

我的目标是获取IF Exists子句中的当前标记,并在update语句中将新数据附加到其中。有什么想法吗?

BEGIN
SET NOCOUNT ON;

IF EXISTS (SELECT id, tags FROM AccountLogAccounts WHERE account = @account)
BEGIN
    UPDATE AccountLogAccounts 
    SET tags = (
        SELECT tags 
        FROM AccountLogAccounts
        WHERE account = @account
    ) + ',' @tags --This doesn't work :)
    WHERE account = @account
END
ELSE
    BEGIN
         INSERT INTO AccountLogAccounts (
            account,
            location,
            tags,
            whoAdded,
            whenAdded
        ) VALUES (
            @account,
            @location,
            @tags,
            @ntid,
            GETDATE()
        )
            END
END

1 个答案:

答案 0 :(得分:2)

而不是......

UPDATE AccountLogAccounts 
    SET tags = (
        SELECT tags 
        FROM AccountLogAccounts
        WHERE account = @account
    ) + ',' @tags --This doesn't work :)
    WHERE account = @account

...尝试...

UPDATE AccountLogAccounts 
    SET tags = tags + ',' + @tags
    WHERE account = @account

修改

这是一个小小的演示(未经测试,但应该有效):

CREATE PROCEDURE UpdateMyText
    @account int,
    @tags nvarchar(max)
AS
UPDATE AccountLogAccounts 
    SET tags = CAST(tags as nvarchar(max)) + ',' + @tags
    WHERE account = @account
GO

EXEC UpdateMyText 12345, 'abc'
GO