0

I am having trouble finding the correct syntax to make this work?

I have a table with the columns id and color and I want to print out all of the id's for a specific color.

if exists(select id from mytable where color = 'red')
    print id


if exists(select id from mytable where color = 'red')
    print SCOPE_IDENTITY() --which won't work because i'm using select rather than insert
2
  • 1
    Why are you using PRINT from SQL? SQL isn't designed to easily "print" the results of a query. Commented Sep 11, 2013 at 21:47
  • It's just a contrived example Commented Sep 11, 2013 at 21:54

3 Answers 3

2

PRINT only prints one value. It looks like you want to loop through the results and print each value, which will require a cursor:

DECLARE @id INT
DECLARE id_cursor CURSOR FOR 
SELECT id from mytable where color = 'red'

OPEN id_cursor

FETCH NEXT FROM id_cursor 
INTO @id

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @id

    FETCH NEXT FROM id_cursor 
    INTO @id
END 
CLOSE id_cursor;
DEALLOCATE id_cursor;

Which seems ridiculous to do in SQL and is why I said in my comment that SQL is not designed to easily print the results of a query - you may be better off returning a result set and letting the consumer print the results.

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

1 Comment

Ok thats what I was looking for sorry about the confusion I tried to simplify my example and I think I made it to simple but the cursor is exactly what I was looking for, thanks.
2

id isnt defined.

The id in the exists subquery doesnt exist outside that subquery.

You could do this:

declare @id int;
select @id = id from table_name;
if (@id is not null) 
    print @id;

3 Comments

Sorry my example wasn't quite right for what I was trying to do, I have just updated it :-)
@jamesla. You still have the problem in your code. ID is a column name, not a variable. You have to declare a variable like John did.
This only prints 1 id rather than all of the id's with the specified color. (not your fault I realised I had omitted this and updated the question after you posted this John).
0

You just need select id from mytable where color = 'red

This will return every id where color is red. If there aren't any, then you will get a single row in the dataset with in the id column

2 Comments

Last sentence isn't correct. If there aren't any, then they will get an empty resultset.
This is technically correct however my example is contrived for the reason that I need to run additional queries using the id, so we need to stick to using print.

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.