我在要查找的表格中有特定信息,此查询将显示:
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个单独的select语句。
这就是我所拥有的,但它并不像我想要的那样工作:
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
我很好奇我是否可以尝试一下?
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:1)
SELECT setting, StringValue
FROM ClientSettings
WHERE Setting in ('CompanyDomain'
,'CompanyActivityEmail'
,'CompanySupportPhone'
,'CompanyName')
然后循环结果并分配变量。
答案 3 :(得分:0)
作为一种替代方法,您可以创建一个名为company_settings
的表,其中Setting
列的值为'CompanyDomain'
,'CompanyActivityEmail'
等。< / p>
然后你可以这样做:
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);