尝试这个
SELECT top 250 * FROM [MyTable]
where
(@Criteria1 = '' or Col1 LIKE '%' + @Criteria1 + '%') and
(@Criteria2 = '' or Col2 LIKE '%' + @Criteria2 + '%') and
(@Criteria3 = '' or Col3 LIKE '%' + @Criteria3 + '%')
这是一些测试代码
create table MyTable
(
id int identity,
col1 nvarchar(50),
col2 nvarchar(50),
col3 nvarchar(50)
)
go
insert into MyTable(col1, col2, col3) values( '', '', '');
insert into MyTable(col1, col2, col3) values( '', '', 'a');
insert into MyTable(col1, col2, col3) values( '', 'a', 'b');
insert into MyTable(col1, col2, col3) values( 'a', 'b', 'c');
insert into MyTable(col1, col2, col3) values( 'b', 'c', '');
insert into MyTable(col1, col2, col3) values( 'c', '', '');
-- select * from MyTable;
go
CREATE PROCEDURE [MyProc]
(
@Criteria1 nvarchar(50),
@Criteria2 nvarchar(50),
@Criteria3 nvarchar(50)
)
AS
select *
from MyTable
where
(@Criteria1 = '' or Col1 LIKE '%' + @Criteria1 + '%') and
(@Criteria2 = '' or Col2 LIKE '%' + @Criteria2 + '%') and
(@Criteria3 = '' or Col3 LIKE '%' + @Criteria3 + '%')
go
exec MyProc '', '', '';
exec MyProc 'a', '', '';
exec MyProc '', 'a', '';
exec MyProc '', '', 'a';