MSSQL-如果第一次返回0,则运行第二个select

时间:2018-11-08 13:08:19

标签: sql sql-server tsql

如果第一个选择不返回任何数据,但我尝试执行,则无法运行。

@Model varchar(50),
@UserId nvarchar(128),
@CountryId int

SELECT
        COUNT(1)
    FROM
        Product P
        JOIN Location PC ON P.ProductId = PC.ProductId
        JOIN Users USR ON USR.CountryId = PC.CountryId
    WHERE
        P.Model = @Model AND USR.Id = @UserId

if @@rowcount = 0
    SELECT
        COUNT(1)
    FROM
        Product P
        JOIN Location PC ON P.ProductId = PC.ProductId
    WHERE
        P.Model = @Model AND PC.CountryId = @CountryId

有2个结果...我怎么只能返回一个?

谢谢。

3 个答案:

答案 0 :(得分:2)

大概,您的问题是关于第一个查询返回的值,而不是行数。

如果是这样,您可以将其写为一个查询:

WITH t1 AS (
      SELECT COUNT(1) as cnt
      FROM Product P JOIN
           Location PC
           ON P.ProductId = PC.ProductId JOIN
           Users USR
           ON USR.CountryId = PC.CountryId
      WHERE P.Model = @Model AND USR.Id = @UserId
     )
SELECT (CASE WHEN cnt > 0 THEN cnt
             ELSE (SELECT COUNT(1)
                   FROM Product P JOIN
                        Location PC
                        ON P.ProductId = PC.ProductId
                   WHERE P.Model = @Model AND PC.CountryId = @CountryId
        END) as cnt
FROM t

答案 1 :(得分:2)

您可以尝试声明变量@Cnt来获取查询量并检入值。

@Model varchar(50),
@UserId nvarchar(128),
@CountryId int,
@Cnt INT

SELECT
    @Cnt = COUNT(1)
FROM
    Product P
    JOIN Location PC ON P.ProductId = PC.ProductId
    JOIN Users USR ON USR.CountryId = PC.CountryId
WHERE
    P.Model = @Model AND USR.Id = @UserId

if (@Cnt == 0)
BEGIN
    SELECT
        @Cnt = COUNT(1)
    FROM
        Product P
        JOIN Location PC ON P.ProductId = PC.ProductId
    WHERE
        P.Model = @Model AND PC.CountryId = @CountryId
END

SELECT @Cnt

答案 2 :(得分:0)

使用该选择语句将不会获得@@ rowcount。参见this similar answer进行澄清。

您可以创建如下所示的变量,并使用它代替@@ rowcount

SELECT @Count=COUNT(1)