如果没有参数传递给存储过程,它应该返回所有结果。
如果我传递任何一个参数,则值应根据参数显示
alter proc SearchEmployee --'','','',''
@Name varchar(50)=null,
@Age int=null,
@Gender varchar(50)=null,
@Email varchar(50)=null
as
begin
declare @sql varchar(max), @sqlwhere varchar(max)
set @sqlwhere = '';
set @sql = 'select * from employee'
if ((@Name is not null) and @Name <> '')
begin
set @sqlwhere=' Name='+ @Name
end
else if ((@Age is not null) and @Age <> '')
begin
set @sqlwhere='and Age='+ cast(@Age as varchar(50))
end
else if ((@Email is not null) and @Email <> '')
begin
set @sqlwhere=' and email='+ @Email
end
else if ((@Gender is not null) and @Gender <> '')
begin
set @sqlwhere=' and Gender='+ @Gender
end
if (@sqlwhere <> '')
begin
set @sql = @sql + ' where ' + @sqlwhere;
end
else
begin
set @sql = @sql;
end
print @sql
exec (@sql)
end
employee
桌子
Name Age Gender email
anurag 24 Male anu@gmail.com
abhi 22 Male abhi@gmail.com
ruchi 23 Female ruchi@gmail.com
siba 24 Male siba@gmail.com
mukua 24 Male mukua@gmail.com
prachi 24 Female prachi@gmail.com
preeti 24 Female preeti@gmail.com
执行
SearchEmployee '','','',''
给我所有的结果。
但是执行以下会出错
SearchEmployee 'anurag','','',''`
select * from employee where Name=anurag
错误:
消息 207,级别 16,状态 1,第 1 行
无效的列名称“anurag”。
请帮我修改查询。我在哪里做错了?