I am trying to write a query that uses variables to feed into a sub query.
Query:
DECLARE @Code VARCHAR(5)
DECLARE @Sys INT
DECLARE @Key INT
SET @Key = 12345
SET @Code = (SELECT Code
FROM LOOKUP.Table1
WHERE Key = @Key)
SET @Sys = (SELECT DISTINCT System
FROM LOOKUP.Table1
WHERE Key = @Key)
SELECT
@Code AS Code,
(SELECT DISTINCT
COUNT(ID)
FROM [LINKED-SERVER].[DB].[SCHEMA].[Table_H]
WHERE [Type] NOT LIKE 'X%'
AND [Key] = @Key
AND [Code] IN (@Code)
) AS Total,
(SELECT
COUNT(Type)
FROM [LINKED-SERVER].[DB].[SCHEMA].[Table_H]
WHERE [Type] LIKE 'Y%'
AND [Key] = @Key
AND [Code] IN (@Code)
) AS TypeA,
(SELECT
COUNT(Type)
FROM [LINKED-SERVER].[DB].[SCHEMA].[Table_H]
WHERE [Type] LIKE 'N%'
AND [Key] = @Key
AND [Code] IN (@Code)
) AS TypeB
The problem comes when [Key]
is used for multiple values of [Code]
:
Msg 512, Level 16, State 1, Line 7
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Some have as many as 5 values. I can't figure out how to make this query work when SET @Code
would return more than 1 value.