如何使用“匿名表”参数化更新?

时间:2012-10-25 18:35:22

标签: sql sql-server ms-access

我很确定我未能找到谷歌答案的很大一部分原因是因为我不知道描述问题的正确术语。

我很清楚以下形式:

UPDATE Table t
SET t.description = Concat(ot.text, ' text')
FROM Table
INNER JOIN Other_Table ot ON t.id = ot.id
WHERE conditions;

我想要完成的更像是:

UPDATE Table t
SET t.description = Concat(item, ' text')
FROM t
INNER JOIN (SELECT item FROM ('list', 'of', 'items'))
WHERE conditions;

换句话说,我有一个“匿名表”,或者在查询中指定的显式字符串列表,而不是存储在表中,我希望它们一次被挑选一个并与一些字符串文字连接起来更新一行。

想象一下,我有一张产品信息表。我想更新此表,以便“说明”列包含“此产品是颜色!”。我正在寻找类似的东西:

UPDATE Products p
SET p.desc = Concat('This product is ', color, '!')
FROM p
INNER JOIN (SELECT color FROM ('blue', 'red', 'green'))
WHERE p.sku in (111, 112, 113);

我正在使用Access 2010并连接到SQL Server 2008数据库。

2 个答案:

答案 0 :(得分:2)

SQL Server 2008允许使用VALUES子句作为表源:

CREATE TABLE products([desc] NVARCHAR(MAX),sku int)


UPDATE p
SET p.[desc] = 'This product is '+ C.color+ '!'
FROM Products p
INNER JOIN (VALUES(111,'blue'),(112, 'red'),(113, 'green')) AS c(sku,color)
ON p.sku = c.sku
WHERE p.sku in (111, 112, 113);

答案 1 :(得分:1)

我不确定我是否正确,但请尝试这样的事情

update Products p set
    p.desc = Concat('This product is ', C.color, '!')
from p
    inner join
    (
        select 'blue' as color, 111 as id union all
        select 'red' as color, 112 as id union all
        select 'green' as color, 113 as id
    ) as C on C.id = p.sku
where p.sku in (111, 112, 113);