开发者

set variable to NULL if nested query returns no results

开发者 https://www.devze.com 2023-03-05 09:38 出处:网络
Suppose you have the following query. If the nested query returns NULL(0 results), the stored procedure crashes with the follow开发者_如何转开发ing error mentioned below.I found out I can re-write the

Suppose you have the following query. If the nested query returns NULL(0 results), the stored procedure crashes with the follow开发者_如何转开发ing error mentioned below. I found out I can re-write the code in the Alternative query below, but I'm wanting to find an easier syntax to write it. I have about 10 of these, and some have multiple nested queries. Is there an easier way to write them? I'm not an expert in SQL, so I'm always looking for suggestions! Thanks.

Query (that sometimes crashes):

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

Error from query:

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

Alternative query that never crashes:

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

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

Example that's more complex:

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


try

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


You set to NULL the records for which do not exist records in sample_table with identifyingnumber equal to sample_identifyingnumber:

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

You set to MIN (DISTINCT sampleid) the field sampleid for which exist in sample_table records where identifying_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);

I have written MIN (DISTINCT ...) in case we find more sampleids corresponding to the same identifyingnumber: in this unlucky case, I take the MINIMUM of the X (with X strictly > 1) different sampleids.

I need two updates instead of one.

0

精彩评论

暂无评论...
验证码 换一张
取 消