用子查询时的情况

时间:2014-09-01 12:42:41

标签: sql sql-server-2008

我尝试在sql中执行像c#这样的切换,或者使用不同的条件。

我使用它但它根本不起作用:

用于存储过程:

CREATE PROCEDURE [dbo].[Mystoredprocedure]
@Value INT
AS 
BEGIN

       SET NOCOUNT ON;
CASE

WHEN @Value = 0
THEN SELECT * FROM mytable1


WHEN @Value = 1
THEN SELECT * FROM mytable2

WHEN @Value = 2
THEN SELECT * FROM mytable3

END

但它不起作用,我搜索的例子,但我找不到我想要的东西。

我也试过:

    CREATE PROCEDURE [dbo].[Mystoredprocedure]
    @Value INT
    AS
    BEGIN
          SET NOCOUNT ON;

    IF @Value = 0
    BEGIN
         SELECT * FROM MyTable1
    END

    ELSE IF @Value = 1
    BEGIN
         SELECT * FROM MyTable2
    END

    ELSE IF @Value = 2
    BEGIN 
         SELECT * FROM Mytable3
    END

END

你有解决方案来解决这个问题吗?谢谢!

2 个答案:

答案 0 :(得分:1)

我建议你试试这个:

CREATE PROCEDURE [dbo].[Mystoredprocedure] (@Value INT)
AS 
BEGIN

    IF @Value = 0
        BEGIN
            SELECT * FROM mytable1
        END
    ELSE IF @Value = 1
        BEGIN
            SELECT * FROM mytable2
        END
    ELSE IF @Value = 2
        BEGIN
            SELECT * FROM mytable3
        END

END

如果我做对了,问题是你的查询中有一个变量,但是你没有传递一个值。你宣布它,它是空的。通过这种方式,如果您调用查询

EXEC [dbo].[Mystoredprocedure] 1

它应该从mytable 2等中选择

答案 1 :(得分:0)

最后我找到了解决方案,这很容易。我只是在if之前移除了else而且它有效!

CREATE PROCEDURE [dbo].[MystoredProcedure]
(@Value INT)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;



IF @Value = 0
BEGIN   
     SELECT * FROM mytable1
END

IF @Value = 1
BEGIN
     SELECT * FROM mytable2
END

IF @Value = 2
BEGIN
    SELECT * FROM mytable3  
END

IF @Value = 3
BEGIN
    SELECT * FROM mytable4
END

END