2

我正在使用 SQL Server 2005 并具有以下 T-SQL 语句:

DECLARE 
    @MP VARCHAR(500)
SELECT
    @MP = COALESCE(@MP + ',','') + [Name] + ',' + '(' + [Political Party] + ')'
FROM [MPs]
WHERE [MPs].[Region] ='Wales' 


UPDATE myTable
SET [Names and parties] = 
(SELECT @MP
WHERE myTable.[Local Region] ='Wales')

This works fine and will populate myTable with @MP where 'Wales' is present; however if I run the statement again, this time with say 'Scotland', all the previously updated entries for 'Wales' will then become NULL in myTable.

I think I'm missing something here - using a different variable name for @MP for the second search doesn't work.

4

2 回答 2

2

我想你可能正在寻找这个:

UPDATE myTable
SET [Names and parties] = @MP
WHERE myTable.[Local Region] = 'Wales'
于 2012-04-04T09:58:34.377 回答
2

第二个 WHERE 子句位于错误的位置。它目前适用于 SELECT,而不是 UPDATE,我认为这是您想要的。

UPDATE myTable 
SET [Names and parties] =  @MP 
WHERE myTable.[Local Region] ='Wales'
于 2012-04-04T10:00:33.990 回答