名为 Emp 的表包含id,name,lname,birthdate,address and salery
。我想从 emp 中进行选择。基本查询:select * from emp
如果传递 lname 的值,查询:select * from emp where lname = 'fgfg'
像这样。所以我创建了以下 sp。
create Procedure Proc_selectEmp
(
@name varchar(10) = null,
@lname varchar(10) = null,
@id varchar(10) = null
)
as
begin
select * from Emp
where
(@name is null or name = @name)
and (@lname is null or lname = @lname)
and (@id is null or id = @id)
end
与 emp 一样,有 13 个表具有相同的列名。所以我的tablenmae也是动态的。这就是为什么,我选择执行sp_executesql。我可以这样创建吗
create Procedure Proc_selectEmp
(
@name varchar(10) = null,
@lname varchar(10) = null,
@id varchar(10) = null
@tableName varchar(30)
)
as
begin
declare @query nvarchar(1000)
set @query = @query +'select * from '+@tableName+'
where ('+@name+' is null or name = '+@name+')
and ('+@lname+' is null or lname = '+@lname+')
and ('+@id+' is null or id = '+@id+')
end'
execute sp_executesql @query