帮助构造条件SQL语句

时间:2010-05-21 17:45:23

标签: sql sql-server tsql

我想用条件IF构造一个SELECT语句。

例如,如果没有语言代码'Swedish'的记录:

SELECT * FROM Entries WHERE Language = 'Swedish'

然后使用'English'

SELECT * FROM Entries WHERE Language = 'English'

我如何使用MSSQL构建此语句?

谢谢,

的Stefan

6 个答案:

答案 0 :(得分:5)

天真:

SELECT *
FROM Entries
WHERE Language = 'Swedish' 

UNION ALL

SELECT *
FROM Entries
WHERE Language = 'English' 
    AND NOT EXISTS (
        SELECT *
        FROM Entries
        WHERE Language = 'Swedish' 
    )

或:

SELECT *
FROM Entries
WHERE Language = 'Swedish' 
    OR (Language = 'English' 
        AND NOT EXISTS (
            SELECT *
            FROM Entries
            WHERE Language = 'Swedish' 
        )
    )

答案 1 :(得分:3)

另一种方法:

Select Top 1 *
From   Entries
Where  Language In ('Swedish', 'English')
Order By Case When Language = 'Swedish' Then 1 Else 2 End

答案 2 :(得分:1)

您可以为此编写存储过程并在代码中使用它,例如

select count(*) into V from entries where language='Swedish'
IF (v>0)
// use swedish
else
// use english

请参阅此example

希望这会有所帮助。

答案 3 :(得分:1)

如果你想在这里设置一个基本陈述,有很多方法可以做到这一点。

IF (SELECT count(*) FROM entries WHERE language = 'english') > 0
BEGIN
    //What you want to do for english
END
ELSE IF (SELECT count(*) FROM entries WHERE language = 'swedish') > 0
BEGIN
  // What you want to do for Swedish
END
ELSE
BEGIN
  // There are no records for those languages!!
END

如果要将其用作存储过程,可以尝试以下操作:

CREATE PROCEDURE GetLanguageRows
    @language varchar(500)
AS

IF (SELECT count(*) FROM entries WHERE language = @language) > 0
BEGIN
   //What you want to do for that language
END
ELSE
BEGIN
  // No records found!
END

现在你可以使用

exec GetLanguageRows 'English'

希望我能帮助上述其他一些好的答案!

答案 4 :(得分:0)

如果存在(从语言='瑞典语'的条目中选择1)然后     开始     SELECT * FROM条目WHERE语言='瑞典语'     结束 其他     开始     选择*来自语言='语言'的条目     端

答案 5 :(得分:0)

SELECT * FROM Entries AS e WHERE Language IN( 'Swedish','English')
  AND NOT EXISTS(
    SELECT * FROM Entries AS e1 WHERE Language IN( 'Swedish','English')
      AND e.Language > e1.Language 
)