使用SQL Server 2005中的case语句从不同表中的相同字段

时间:2010-07-14 07:21:34

标签: sql-server-2005

我对SQL Server专业知识有一个不那么难的问题。虽然我有另一种选择,但我想知道这可以解决使用SQL Server 2005中的CASE语句。

我有各种具有相同列的类别表。我需要的是根据类别调用SELECT语句。以下是我正在尝试做的代码

ALTER PROCEDURE [dbo].[Sgi_DropDownListItemsLoadByTblName] 
    @Category int
AS
BEGIN
    SET NOCOUNT ON;


    CASE
        when @Category = 1 Then Select [ID],[OptionText],[Description] From dbo.Sgi_ListItems_Denomination
        when @Category = 2 Then Select [ID],[OptionText],[Description] From dbo.Sgi_ListItems_Drink
        when @Category = 3 Then Select [ID],[OptionText],[Description] From dbo.Sgi_ListItems_Education
        when @Category = 4 Then Select [ID],[OptionText],[Description] From dbo.Sgi_ListItems_Ethnicity
        when @Category = 5 Then Select [ID],[OptionText],[Description] From dbo.Sgi_ListItems_Kids
        when @Category = 6 Then Select [ID],[OptionText],[Description] From dbo.Sgi_ListItems_Religion
        when @Category = 7 Then Select [ID],[OptionText],[Description] From dbo.Sgi_ListItems_Smoking
    end
END

当我尝试创建此SP时,会在CASE语句

上生成错误

我知道这可以使用简单的IF语句来完成,但我很想知道如何使用CASE语句来完成它。

任何人都可以帮助我。

感谢您分享您的时间。

1 个答案:

答案 0 :(得分:2)

好吧,你可以使用动态sql,但我不认为你所寻找的是可能的。但是,有人会让我感到惊讶。请参阅下面的快速和脏版本。

DECLARE @Statement varchar(max)
SET @Statement = 'Select [ID],[OptionText],[Description] From '

DECLARE @Category int
SET @Category = 5

SELECT @Statement = @Statement + 
    CASE
        when @Category = 1 Then 'dbo.Sgi_ListItems_Denomination'
        when @Category = 2 Then 'dbo.Sgi_ListItems_Drink'
        when @Category = 3 Then 'dbo.Sgi_ListItems_Education'
        when @Category = 4 Then 'dbo.Sgi_ListItems_Ethnicity'
        when @Category = 5 Then 'dbo.Sgi_ListItems_Kids'
        when @Category = 6 Then 'dbo.Sgi_ListItems_Religion'
        when @Category = 7 Then 'dbo.Sgi_ListItems_Smoking'
    end

EXEC(@Statement)