如果嵌套查询没有返回结果,则将变量设置为NULL

时间:2011-05-13 08:42:40

标签: sql syntax subquery

假设您有以下查询。如果嵌套查询返回NULL(0结果),则存储过程将崩溃并出现以下错误。我发现我可以在下面的Alternative查询中重写代码,但是我想找到一个更简单的语法来编写代码。我有大约10个,有些有多个嵌套查询。有没有更简单的方法来编写它们?我不是SQL的专家,所以我一直在寻找建议!感谢。

查询(有时会崩溃):

SET @sampleid = (
    SELECT 
        [sampleid]
    FROM [sample]
    WHERE [identifyingnumber] = @sample_identifyingnumber

查询错误:

Subquery returned more than 1 value. This is not permitted when the subquery
follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

永不崩溃的替代查询:

IF 
(
    SELECT 
        COUNT([sampleid])
    FROM [sample]
    WHERE [identifyingnumber] = @sample_identifyingnumber
) = 0
BEGIN
SET @sampleid = NULL
END
ELSE
BEGIN
SET @sampleid =
(
    SELECT 
        DISTINCT [sampleid]
    FROM [sample]
    WHERE [identifyingnumber] = @sample_identifyingnumber
)
END

===============

更复杂的例子:

SET @testcodeid = (
    SELECT 
        [testcodeid]
    FROM [testcode]
    WHERE [testcode].[name] = (
        SELECT [test_code]
        FROM [ws_test_request]
        WHERE [client_id] = @clientid
          AND [sample_specimen_id] = @sample_identifyingnumber
    )
);  

2 个答案:

答案 0 :(得分:2)

SELECT @sampleid = [sampleid]
FROM [sample]
WHERE [identifyingnumber] = @sample_identifyingnumber

答案 1 :(得分:0)

将sample_table中不存在记录的记录设置为NULL,其标识号等于sample_identifyingnumber:

UPDATE my_table
   SET sampleid = NULL
 WHERE NOT EXISTS
          (SELECT 'X'
             FROM sample_table
            WHERE identifyingnumber = sample_identifyingnumber);

您将sample_table记录中存在的字段sampleid设置为MIN(DISTINCT sampleid),其中identify_number = sample_identifyingnumber:

UPDATE my_table
   SET sampleid =
          (SELECT MIN (DISTINCT sampleid)
             FROM sample_table
            WHERE identifyingnumber = sample_identifyingnumber)
 WHERE EXISTS
          (SELECT 'X'
             FROM sample_table
            WHERE identifying_number = sample_identifyingnumber);

我写了MIN(DISTINCT ...)以防我们发现更多的样本对应于相同的识别号码:在这个不幸的情况下,我采用X的最小值(X严格> 1)不同的样本。

我需要两个更新而不是一个。