I have a table with 2 columns-
I have ac# function which calls a stored procedure
...
cmd.Parameters.Add(new SqlParameter("@aa", SqlDbType.Int));
cmd.Parameters["@aa"].Value = aaValue;
cmd.Parameters.Add(new SqlParameter("@bb", SqlDbType.Int));
cmd.Parameters["@bb"].Value = bbValue?? (object)DBNull.Value;
reader = cmd.ExecuteReader(); ...
Now I want the stored procedure to return all the entries which have "aa" equal to aaValue and "bb" equal to bbValue. but if bbValue is null, i want to return all the entries only with "aa" equal to aaValue.
How can I write such a stored procedure?
Here is what I have done, but it doesn't work
SELECT ID
FROM MyTable
WHERE aa = @aa AND (bb IS NULL OR bb = @bb)
For what it is worth, you will find this approach has suboptimal performance, this line (when corrected)
(@bb is null OR bb = @bb)
Means that any index on bb
cannot be used, because at compile time it is not known whether or not @bb
will be NULL
, so a query plan that caters for both scenarios will be chosen. It would be better to separate your queries with and IF/ELSE
flow operator, that way two plans can be cached, one for when @bb
is NULL
and one for when it isn't:
IF @bb IS NULL
BEGIN
SELECT ID
FROM MyTable
WHERE aa = @aa;
END
ELSE
BEGIN
SELECT ID
FROM MyTable
WHERE aa = @aa
AND bb = @bb;
END
您只是忘记了@bb变量的@,因为您只需要检查变量是否有效,而不是检查行值是否为null
SELECT ID from MyTable where aa = @aa and (@bb is null OR bb = @bb)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.