如果沒有參數傳遞給存儲過程,則應返回所有結果。存儲過程中的動態sql無法獲取所需結果
如果我通過任何一個參數值,然後應顯示爲每個參數
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 [email protected]
abhi 22 Male [email protected]
ruchi 23 Female [email protected]
siba 24 Male [email protected]
mukua 24 Male [email protected]
prachi 24 Female [email protected]
preeti 24 Female [email protected]
執行
SearchEmployee '','','',''
給了我所有的結果。
但執行列出了錯誤
SearchEmployee 'anurag','','',''`
select * from employee where Name=anurag
錯誤:
Msg 207, Level 16, State 1, Line 1
Invalid column name 'anurag'.
請幫我修改查詢。我在哪裏做錯了?
這個'select * from employee where Name = anurag'試圖找到行'名稱'列匹配'anurag'列的值 - 但有**沒有** 'anurag'專欄!你需要把你的字符串值放入**單引號!** - 'select * from employee where Name ='anurag'' –