1

What's wrong with this?

  DECLARE @error int

  If (SELECT ID_Projet FROM tblProjet WHERE No_Projet=@no_Projet)> 0
     SET @error=1
  END IF
4
  • 3
    What is it supposed to do? Are you trying to test if there are >0 matching rows or test whether the ID_Projet value is >0? Commented Feb 10, 2012 at 16:45
  • Are you getting an error? What is it? Commented Feb 10, 2012 at 16:45
  • are you trying to check number of rows returned or ID_Project is a field in the database? Commented Feb 10, 2012 at 16:46
  • Yes this is what I try Martin. Do you have a better solution? Commented Feb 10, 2012 at 17:02

2 Answers 2

6

The END IF is incorrect.

Do it like this:

 DECLARE @error int

  If (SELECT ID_Projet FROM tblProjet WHERE No_Projet=@no_Projet)> 0
     SET @error=1

or this:

 DECLARE @error int

  If (SELECT ID_Projet FROM tblProjet WHERE No_Projet=@no_Projet)> 0
  Begin
     SET @error=1
  End

Check HERE for documentation.


If you're trying to see the number of rows with that restriction you should do it like this:

 DECLARE @error int

  If (SELECT count(ID_Projet) FROM tblProjet WHERE No_Projet=@no_Projet)> 0
  Begin
     SET @error=1
  End
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for correct answer and if I could another +1 for being faster at typing than me!
If you are only checking if the condition is met then it should use IF EXISTS as then the table scan only goes to the first match rather than a full table scan to count the records.
3

END IF is not T-SQL syntax for conditional statements.

DECLARE @error int

IF (SELECT COUNT(ID_Projet) FROM tblProjet WHERE No_Projet=@no_Projet)> 0
  BEGIN
    SET @error=1
  END 

EDIT:

Since this is only checking for at least one row you should use the EXISTS functionality rather than COUNT. This is much more efficient, if ID_Project is nullable you will need to add a further WHERE clause to the EXISTS Query to add "AND ID_Projet IS NOT NULL" since COUNT(NULL) = 0

DECLARE @error int

IF EXISTS(SELECT ID_Projet FROM tblProjet WHERE No_Projet=@no_Projet)
  BEGIN
    SET @error=1
  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.