SQL Server:作为存储过程执行的结果返回select的结果

时间:2017-06-16 13:43:18

标签: c# sql-server-2008 stored-procedures

我有一个从C#调用的存储过程:

CREATE PROCEDURE [MySP] 
    @ID int,
    @Exists bit OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    SET @Exists = 0

    SELECT TOP 1 ID 
    FROM MyTable 
    WHERE ID = @ID

    IF @@ROWCOUNT = 0
    BEGIN
        SELECT b.*
        FROM AnotherTable b
        INNER JOIN AnotherTable2 c ON b.ID = c.ID
        WHERE b.ID = @ID            
   END
   ELSE
   BEGIN
       SET @Exists = 1

       SELECT TOP 0 NULL
   END
END

如果表@ID中不存在MyTable,则返回SELECT b.*,否则如果表中存在@ID,则表示不返回任何行

问题是,当表中存在@ID时,存储过程会将两个表作为结果返回给C#,一个来自SELECT TOP 1,一个来自SELECT b.*而我只返回想要返回SELECT b。*所以我该怎么做?

3 个答案:

答案 0 :(得分:3)

只需将所有逻辑替换为:

SELECT b.*
From AnotherTable b INNER JOIN
     AnotherTable2 c
     ON b.ID = c.ID
WHERE b.ID = @ID AND
      NOT EXISTS (SELECT 1 FROM MyTable WHERE ID = @ID);

而且,如果你不想要重复,你也可以这样做:

SELECT b.*
From AnotherTable b 
WHERE b.ID = @ID AND
      EXISTS (SELECT 1 FROM AnotherTable2 c WHERE b.ID = c.ID) AND
      NOT EXISTS (SELECT 1 FROM MyTable WHERE ID = @ID);

然后,了解表值函数。如果要返回一个表,那么最好的方法 - 如果可行 - 是一个函数,而不是一个存储过程。 (功能在功能上更受限制,因此并非总是可行。)

答案 1 :(得分:1)

使用存在:

CREATE PROCEDURE [MySP] 
    @ID int,
    @Exists bit OUTPUT
AS
BEGIN

    SET NOCOUNT ON;

   SET @Exists = 0


   IF EXISTS(SELECT TOP 1 ID FROM MyTable WHERE ID = @ID)
   BEGIN
        SELECT b.*
        From   AnotherTable b
               INNER JOIN AnotherTable2 c on b.ID = c.ID
        Where  b.ID = @ID            
   END
   ELSE

   BEGIN
       SET @Exists = 1
       SELECT TOP 0 NULL
   END
END

答案 2 :(得分:0)

您获得的第二个结果来自语句select top 0 null