2012-12-13 107 views
1

我有一個簡單的表如下SQL選擇使用多列多個變量,其中

CREATE TABLE [accounting].[ExtractControl](
    [SourceSchema] [varchar](50) NOT NULL, 
    [SourceTable] [varchar](150) NOT NULL, 
    [SourceDatabase] [varchar](50) NOT NULL) 

我想選擇使用SourceSchemasourceTable會

目前我SourceDatabase按如下方式進行多項查詢:

Select @s1 = SourceDatabase from accounting.ExtractControl where SourceSchema = 'xxx' and SourceTable = 'xxx' 
Select @s2 = SourceDatabase from accounting.ExtractControl where SourceSchema = 'yyy' and SourceTable = 'yyy' 
Select @s3 = SourceDatabase from accounting.ExtractControl where SourceSchema = 'xxx' and SourceTable = 'yyy' 

我確實認爲這可以用更優雅的方式來完成!謝謝您的幫助!

+1

你覺得沒有用你目前的解決方案來優雅嗎? –

+0

@DanielHilgarth我在查詢數據庫3次返回3個變量,我想也許它可能返回所有3變量使用1查詢對Db。 – dopplesoldner

回答

1

你是否在問這樣的事情?

select SourceDatabase from accounting.ExtractControl 
where SourceSchema in ('xxx', 'yyy') and SourceTable in ('xxx', 'yyy'); 

這將返回SourceDatabase其中SourceSchema要麼是 'XXX' 或 'YYY' 和SourceTable要麼是 'XXX' 或 'YYY'。

+0

嗨丹尼爾 它確實會返回SourceDatabase,但我希望它們存儲在不同的變量,取決於SourceSchema和SourceTable 例如,當SourceSchema和SourceTable都是'xxx'時,s1應該是'xxx' s2 - >當兩者都是'yyy'時......等等 – dopplesoldner

+0

如果您確實需要三個不同的變量,請使用您當前的解決方案。 –

+0

@dopplesoldner:同意丹尼爾:如果你想要三個不同的變量的三個結果,保持你目前的解決方案。然而,如果你更詳細地說明你將如何使用這些變量,它可能會導致更好的方法(或者它可能不會)。 –

0
select * from accounting.ExtractControl 
where SourceSchema = 'xxx' or SourceSchema = 'yyy' 
+0

嗨Mert 我希望他們被存儲在不同的變量取決於SourceSchema和SourceTable 例如, s1應該是當SourceSchema和SourceTable都是'xxx's2 - >兩者都是'yyy'時......等等 – dopplesoldner

+0

我不認爲有更好的辦法。你可以在你的代碼中選擇像這樣和linq。 – Mert

1

一個查詢

SELECT @s1 = MAX(CASE WHEN SourceSchema = 'xxx' and SourceTable = 'xxx' THEN SourceDatabase END), 
     @s2 = MAX(CASE WHEN SourceSchema = 'yyy' and SourceTable = 'yyy' THEN SourceDatabase END), 
     @s3 = MAX(CASE WHEN SourceSchema = 'xxx' and SourceTable = 'yyy' THEN SourceDatabase END) 
FROM accounting.ExtractControl 

演示上SQL Fiddle

0

怎麼樣這個查詢...選項

select SourceDatabase 
from accounting.ExtractControl 
where SourceSchema in ('xxx', 'yyy') 
     and SourceTable in ('xxx', 'yyy') 
     and SourceTable = SourceSchema 

我沒有試過,但我認爲這是什麼你需要

+0

如果你想要每個單元格的值不同varriable然後用光標現在 –