2013-10-30 62 views
0

我有一個包含帳號和標籤(關鍵詞)的表。我的查詢將檢查該帳戶是否存在,如果存在,則需要將新關鍵字附加到已經存在的關鍵字上。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 
+0

那麼該怎麼辦? –

+0

我需要從exist語句(當前標記)中獲取結果,並在更新語句中將新數據附加到它。 – SBB

回答

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 
+0

「數據類型文本和varchar在添加操作符中不兼容。」 – SBB

+0

@SSB你需要停止使用'TEXT'數據類型。你應該使用'VARCHAR(MAX)',而不是這個問題。 – RBarryYoung

+0

文本(和ntext)已被棄用,所以您應該用varchar替換它們。同時,只需將您的文本字段作爲varchar。 – Andrew