我对sql语句有疑问。是否有可能以这种方式进行查询?我需要过滤一个取决于@user_id值的where子句。
ALTER PROCEDURE [dbo].[getUserAddress]
@user_id int = null
AS
SELECT user_id, state_code, address from UserAddress
IF(@user_id > 10)
BEGIN
WHERE state_code = 'CA'
END
ELSE
WHERE address = 'HILLS'
END
我尝试这样做,但似乎不是一种标准方式。
IF(@user_id > 10)
BEGIN
SELECT user_id, state_code, address from UserAddress WHERE state_code = 'CA'
END
ELSE
SELECT user_id, state_code, address from UserAddress WHERE address = 'HILLS'
END
请告知这个概念的最佳方法是什么。请帮忙。 感谢
答案 0 :(得分:2)
您begin
后遗漏了else
。试试这个:
IF(@user_id > 10)
BEGIN
SELECT user_id, state_code, address from UserAddress WHERE state_code = 'CA'
END
ELSE
BEGIN
SELECT user_id, state_code, address from UserAddress WHERE address = 'HILLS'
END
答案 1 :(得分:2)
您可以简化:
select
user_id,
state_code,
address
from
UserAddress
where
(@user_id > 10 and state_code = 'CA') or
(@user_id IS NULL OR (@user_id <= 10 and address = 'HILLS'))
如果您将来添加更多过滤条件,您应该了解参数嗅探。
另外,在(user_id, state_code, address)
上创建索引将是此查询的覆盖索引。
答案 2 :(得分:1)
您还可以在存储过程中使用动态SQL查询。
<强>查询强>
declare @sql as varchar(max);
select @sql = 'select * from [UserAddress] '
+ stuff((select case when @user_d > 10
then 'where state_code= ''CA'''
else 'where address = ''Hills''' end
for xml path('')), 1,0,'')
exec(@sql);
答案 3 :(得分:0)
而不是这个用法可以在where语句中使用case:
SELECT user_id, state_code, address from UserAddress WHERE
(case when @user_id > 10 then state_code else address end)
= (case when @user_id > 10 then 'CA' else 'HILLS' end)
答案 4 :(得分:0)
试试这个
zipWith
答案 5 :(得分:0)
你可以简单地......
WHERE
(@user_id > 10 AND state_code = 'CA')
OR ((@user_id <= 10 OR @user_id IS NULL) AND address = 'HILLS')
但是,这种方法可能无法产生最佳查询计划。如果结果是一个问题,请使用单独的查询(正如您已经尝试过的那样,但修复了AsheraH建议的语法错误)或动态SQL。
顺便说一句,你可以更简洁地编写单独的查询:IF @user_id > 10
SELECT user_id, state_code, address from UserAddress WHERE state_code = 'CA'
ELSE
SELECT user_id, state_code, address from UserAddress WHERE address = 'HILLS'
答案 6 :(得分:-2)
你可以试试这个:
ALTER PROCEDURE [dbo]。[getUserAddress]
@user_id int = null
AS
BEGIN
声明@sql nvarchar(5000)
set @sql ='SELECT user_id,state_code,来自UserAddress的地址'
IF(@user_id&gt; 10)
BEGIN
设置@sql = @sql +'WHERE state_code =''CA'''
END
ELSE
设置@sql = @sql +'WHERE address =''HILLS'''
END
Exec的(@sql)
END