Question

The following procedure sets a boolean value based on the rowcounts of each of the following queries and it is then supposed to return the true(1) or false(0) value back to Access; I am currently getting the error of "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS." How can I get this to work?

 CREATE FUNCTION [dbo].[FN_chk](@pF NVARCHAR(255), @pI NVARCHAR(100), 
    @pL NVARCHAR(100), @pLY NVARCHAR(100))

RETURNS INT AS
BEGIN

    DECLARE @Bool BIT
    SET @Bool = 0

    -- check allDataTemp
    If ((SELECT DISTINCT theFN, theIN, theLN, theANA FROM aDT
        WHERE theFN = @pF  and theIN = @pI 
        and theLN = @pL  and theANA = @pLY) > 0)
        BEGIN
            SET @Bool = 1
            RETURN @Bool
        END 

    -- check allDataTemp2
    If ((SELECT theFN, theIN, theLN, theANA FROM aDT2
        GROUP BY theFN, theIN, theLN, theANA 
        HAVING theFN = @pF  and theIN = @pI 
        and theLN = @pL  and theANA = @pLY) > 0)
        BEGIN
            SET @Bool = 1
            RETURN @Bool
        END 

    -- Return the result of the function
    RETURN @Bool

END
Was it helpful?

Solution

As the ERROR already explains, use EXISTS

 If (EXISTS(SELECT DISTINCT theFN FROM aDT
    WHERE theFN = @pF  and theIN = @pI 
       and theLN = @pL  and theANA = @pLY))
    BEGIN
        SET @Bool = 1
        RETURN @Bool
    END

Similarly change the other IF too...
EDIT: EXISTS is used when the number of rows could be zero. Also if you SELECT just one value to compare, it should work too.

OTHER TIPS

Your query inside the IF returns a large number of columns. Comparing this to a number is meaningless. (eg is "Coding", "Maniac" > 0?)

The quickest fix is to switch to using exists

If exists (SELECT DISTINCT theFN, theIN, theLN, theANA FROM aDT
    WHERE theFN = @pF  and theIN = @pI 
    and theLN = @pL  and theANA = @pLY)
    BEGIN

More optimally, don't both with the columns at all - all you are about is that there are rows:

If exists (SELECT count(1) FROM aDT
    WHERE theFN = @pF  and theIN = @pI 
    and theLN = @pL  and theANA = @pLY) 
    BEGIN
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top