I had posted a similar question earlier - a slightly different requirement here.

I have a textBox which returns the user-selected 'Number' value.(eg. : 100,200,300)

What needs to be done is basically check a table MyTable if a record/records exist for the particular Number value selected by user. If it returns NULL, then I need to return the records for the default Number value of 999.

MyTable:
id Number MyVal
1  100    55
2  200    66
3  400    22
4  400    12
5  999    23
6  999    24

Here's what I have so far :(Assuming textBoxInput(Number) = 300)

SELECT Myval 
from MyTable 
where id in (
    SELECT ISNULL(
        SELECT id 
            from MyTable 
            where Number=300, 
        select id 
            from MyTable 
            where Number = 999
    )
)

So here, since Number=300 does not exist in the table, return the records for Number=999.

But when I run this query, I'm getting an error 'Subquery returned more than 1 value...'

Any suggestions/ideas?

有帮助吗?

解决方案

This should work:

SELECT Myval 
from MyTable 
where Number = @Number
OR (NOT EXISTS(SELECT * FROM MyTable WHERE Number = @Number) AND Number = 999)

其他提示

SELECT id, Myval 
  FROM MyTable 
 WHERE id = @id
UNION
SELECT id, 999 AS Myval
  FROM MyTable 
 WHERE id = 999
       AND @id IS NULL;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top