如何在T-SQL中分配多个内联变量?

时间:2013-01-09 20:20:12

标签: sql sql-server tsql subquery

我试图从子查询中选择多个变量以便以后使用。这是我的代码:

DECLARE @MarketplaceName VARCHAR(50),
    @ProductFieldID INT,
    @FromValue VARCHAR(255) = (
        SELECT mcvm.MarketplaceName,
            mcvm.ProductFieldID,
            mcvm.FromValue
        FROM [Meta].[MarketplaceCategoryValueMapping] AS mcvm
        WHERE mcvm.MarketplaceCategoryValueMappingID = @MapID
        )

我收到以下错误消息:

  

当子查询未与EXISTS一起引入时,只能在选择列表中指定一个表达式。

我正在尝试从@MarketplaceName等地点mcvm.MarketplaceName

我想要的是不必为每个变量编写多个SELECT语句。

2 个答案:

答案 0 :(得分:8)

你想这样做吗?

DECLARE @MarketplaceName VARCHAR(50),
        @ProductFieldID INT,
        @FromValue VARCHAR(255)
SELECT  @MarketplaceName    = mcvm.MarketplaceName,
        @ProductFieldID     = mcvm.ProductFieldID,
        @FromValue          = mcvm.FromValue
FROM [Meta].[MarketplaceCategoryValueMapping] AS mcvm
WHERE mcvm.MarketplaceCategoryValueMappingID = @MapID

答案 1 :(得分:3)

这是你如何做到的。此外,这不是一个子查询,它只是一个查询。

DECLARE @MarketplaceName VARCHAR(50),
        @ProductFieldID INT,
        @FromValue VARCHAR(255)


SELECT @MarketplaceName = mcvm.MarketplaceName,
       @ProductFieldID = mcvm.ProductFieldID,
       @FromValue = mcvm.FromValue
FROM [Meta].[MarketplaceCategoryValueMapping] AS mcvm
WHERE mcvm.MarketplaceCategoryValueMappingID = @MapID