1

I want to check in SQL whether a given value exists in one of my tables inside a stored procedure. This is the method I used:

IF( (SELECT COUNT([ID]) FROM my_Table WHERE [Col] = @SP_Parameter) > 0)
BEGIN
   --My Code
END

But that statement is never true no matter what. I made sure the row exists, but it never runs as true.

5
  • 1
    which database system are you using? Commented Dec 19, 2018 at 12:34
  • 1
    SQL (the query language) has no IF statement Commented Dec 19, 2018 at 12:37
  • What is the type of @SP_Parameter and what is the collation of Database? Commented Dec 19, 2018 at 13:11
  • @a_horse_with_no_name, it does. Commented Dec 21, 2018 at 10:23
  • No. SQL the query language does not have an IF statement. Microsoft's SQL Server uses T-SQL which does indeed have IF statement - but that is not part of "SQL" (the standardized query language) Commented Dec 21, 2018 at 10:25

3 Answers 3

4

If your code doesn't work, then nothing matches the WHERE clause. Or, you are misinterpreting the results.

This answer will not fix that problem. But the better way to write the condition is:

IF (EXISTS (SELECT 1 FROM my_Table WHERE [Col] = @SP_Parameter) )
BEGIN
   --My Code
END;

This is less expensive than doing an aggregation query because it can stop at the first matching row.

Sign up to request clarification or add additional context in comments.

2 Comments

But on the other hand they use COUNT([ID]) thus ignoring NULLs in [ID] (unless that column is declared NUT NULL, which doesn't seem unlikely but we don't know). So it might be necessary to extend the WHERE clause with a AND [ID] IS NOT NULL.
It also works for the: IIF(Exists(select 1 from my_table where col = @SP_parameter),true,false) learn.microsoft.com/en-us/sql/t-sql/functions/… If somebody is looking for that.
1

You can use EXISTS () in SQL. try this query

IF EXISTS( SELECT top 1 [ID] FROM my_Table WHERE [Col] = @SP_Parameter )
BEGIN
   --My Code
END

Comments

0
IF EXISTS (SELECT 1 FROM dbo.EmployeeAllowedStatuses WHERE EmployeeAllowedStatuses_ID=EmployeeAllowedStatuses_ID)
BEGIN
    SELECT 'RECORD ALREADY EXISTS' as Result
END
ELSE
BEGIN
    SELECT 'RECORD NOT EXISTS' as Result
END


IF NOT EXISTS (SELECT 1  FROM dbo.EmployeeAllowedStatuses WHERE EmployeeAllowedStatuses_ID=EmployeeAllowedStatuses_ID)
BEGIN
    SELECT 'RECORD NOT EXISTS' as Result
END
ELSE
BEGIN
    SELECT 'RECORD ALREADY EXISTS' as Result

END

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.