0

I'm trying to perform a simple IF statement. I have a table named 'products' that has a column count which is a current count of that specific product in stock. The count column in the database is of data type INT.

I can only get this to work if I statically assign the variable @count. If I assign a select statement to @count the script fails. Even though running the query alone will return a result.

Working query:

DECLARE @count INT
SET @count = 2

IF (@count > 1)
    BEGIN
        PRINT 'It works!'
    END

Failing query:

DECLARE @count INT
SET @count = (SELECT TOP 1 count from products WHERE count > 1)

IF (@count > 1)
    BEGIN
        PRINT 'It works!'
    END
7
  • 1
    SELECT TOP 1 count from products WHERE count > 1 What is the result when you run this query Commented Aug 24, 2015 at 14:45
  • possible duplicate of SET versus SELECT when assigning variables? Commented Aug 24, 2015 at 14:46
  • 1
    "count" is column name in your products table, right? Commented Aug 24, 2015 at 14:46
  • SELECT TOP 1 [count] from products WHERE [count] > 1 Commented Aug 24, 2015 at 14:47
  • You may also find this worth a read.programmers.stackexchange.com/questions/194446/… Commented Aug 24, 2015 at 14:50

3 Answers 3

1

You'd normally use EXISTS

IF EXISTS (SELECT * from products WHERE count > 1)
    BEGIN
        PRINT 'It works!'
    END
Sign up to request clarification or add additional context in comments.

1 Comment

Yes and this query is expected to act slightly different. My end result is that I need all rows where [count] > 1 to be inserted (duplicate rows) and have the total count dropped by one. I was simply attempting to break down my question to the lowest level :)
0

Try:

DECLARE @count INT
SET @count = isnull((SELECT TOP 1 [count] from products WHERE [count] > 1),0)
IF (@count > 1)
    BEGIN
        PRINT 'It works!'
    END

count is a SQL Keyword that's why you need to use [] when you are using any keywords as a column Name.

Comments

0

Instead of having set= select simply use select to assign value to variable also COUNTis a key word in sql server use square brackets [] around it if you want sql server to treat it as an object name..... try this....

DECLARE @count INT
SELECT TOP 1 @count =  [count] from products WHERE count > 1

IF (@count > 1)
    BEGIN
        PRINT 'It works!'
    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.