2

我正在查找的表中有特定信息,此查询将显示它:

SELECT StringValue FROM ClientSettings
WHERE Setting like 'CompanyDomain'
OR Setting like 'CompanyActivityEmail'
OR Setting like 'CompanySupportPhone'
OR Setting like 'CompanyName'

它返回以下日期:

StringValue
MyCompanyName
MyCompanyName@email.com
www.mycompanydomain.com
801-555-1212

我现在尝试将这些设置为变量,而不必制作 4 个单独的选择语句。

这是我所拥有的,但它没有按我的意愿工作:

DECLARE @CompanyName VARCHAR(100)
DECLARE @CompanyDomain VARCHAR(100)
SELECT @CompanyName = StringValue, @CompanyDomain = StringValue FROM ClientSettings
WHERE Setting like 'CompanyName'
OR Setting like 'CompanyDomain'

SELECT @CompanyName
SELECT @CompanyDomain

我很好奇我什至尝试的东西是否可能?

4

4 回答 4

4

我认为问题在于您应该只为每一行分配一个值,而不是同时覆盖其他变量。一个CASE声明应该让你这样做:

DECLARE @CompanyName VARCHAR(100)
DECLARE @CompanyDomain VARCHAR(100)

SELECT 
    @CompanyName = CASE WHEN Setting = 'CompanyName' 
        THEN StringValue ELSE @CompanyName END, 
    @CompanyDomain = CASE WHEN Setting = 'CompanyDomain' 
        THEN StringValue ELSE @CompanyDomain END
FROM ClientSettings
WHERE Setting like 'CompanyName'
OR Setting like 'CompanyDomain'

SELECT @CompanyName
SELECT @CompanyDomain
于 2012-04-06T17:18:43.210 回答
4

您可以使用 PIVOT 来执行此操作,但它有点 hacky,因为它需要使用聚合才能工作

DECLARE @CompanyName VARCHAR(100) 
DECLARE @CompanyDomain VARCHAR(100) 

SELECT @CompanyName = [CompanyName], 
       @CompanyDomain = [CompanyDomain] 
FROM   (SELECT setting, 
               stringvalue 
        FROM   clientsettings 
        WHERE  setting LIKE 'CompanyName' 
                OR setting LIKE 'CompanyDomain') AS sourcetable PIVOT ( MAX( 
       stringvalue 
       ) FOR setting IN ([CompanyName], [CompanyDomain]) ) AS pivottable

SELECT @CompanyName, 
       @CompanyDomain 

工作演示

于 2012-04-06T17:19:13.170 回答
1
SELECT setting, StringValue 
FROM ClientSettings
WHERE Setting in ('CompanyDomain'
                  ,'CompanyActivityEmail'
                  ,'CompanySupportPhone'
                  ,'CompanyName')

然后循环结果并分配您的变量。

于 2012-04-06T17:17:09.830 回答
0

作为一种替代方法,您可以创建一个名为的表,例如company_settings,其中的单列Setting具有值'CompanyDomain''CompanyActivityEmail'

然后你可以这样做:

SELECT StringValue FROM ClientSettings
WHERE Setting is in (select Setting from company_settings);

或者简单地说:

SELECT StringValue 
FROM ClientSettings a
JOIN company_settings b
ON (a.Setting=b.Setting);
于 2012-04-06T17:24:22.773 回答