Suppose you have the following query. If the nested query returns NULL(0 results), the stored procedure crashes with the following 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