简体   繁体   English

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

[英]SQL Server: return the result of a select as a result of stored procedure execution

I have a stored procedure that is called from C#: 我有一个从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

IF @ID does not exist in table MyTable , then I return the SELECT b.* , otherwise if @ID exists in the table, then I return no rows 如果@ID在表MyTable中不存在,则返回SELECT b.* ,否则,如果表中存在@ID ,则不返回任何行

The problem is that when @ID exists in the table, the stored procedure returns two tables as a result to C#, the one from SELECT TOP 1 and the one from SELECT b.* and I only want to return SELECT b.* so how can I do this? 问题是,当表中存在@ID时,存储过程将结果返回两个表到C#,一个返回到SELECT TOP 1 ,另一个返回到SELECT b.*而我只想返回SELECT b。*。我可以这样做吗?

Just replace all the logic with: 只需将所有逻辑替换为:

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);

And, if you don't want duplicates, you might as well do: 而且,如果您不想重复,也可以这样做:

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);

Then, learn about table valued functions. 然后,了解表值函数。 If you want to return a table, then the best approach -- if it is feasible -- is a function, not a stored procedure. 如果要返回表,则最好的方法(如果可行)是函数而不是存储过程。 (Functions are more limited in their functionality, so this is not always possible.) (功能在功能上受到更多限制,因此并不总是可能的。)

Use exists for this: 存在以下用途:

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

您得到的第二个结果是从语句中选择top 0 null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM