我有以下存储过程:
ALTER PROCEDURE [dbo].[Provider]
(@strPro varchar(200))
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT *
FROM [db1].[dbo].[table1]
WHERE [Name] = @strPro
END
我有一个下拉列表,其中包含以下条目:
All People
John D.
Mike K.
Alan H.
Paul Q.
如何修改存储过程,以便用户选择All People
WHERE
语句为LIKE
而不是=
符号
示例:
ALTER PROCEDURE [dbo].[Provider]
(@strPro varchar(200))
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT *
FROM [db1].[dbo].[table1]
if @strPro = 'All People'
BEGIN
WHERE [Name] LIKE '%'
END
ELSE
BEGIN
WHERE [Name] = @strPro
END
END
答案 0 :(得分:7)
喜欢这个
SELECT * FROM [db1].[dbo].[table1]
WHERE @strPro = 'All People' OR [Name] = @strPro
如果传递“所有人” - 第一个条件将为真且所有记录将被返回(您不需要执行LIKE '%'
)否则只会返回匹配[名称]的记录。
答案 1 :(得分:1)
尝试这样的事情,在存储过程中构建SQL语句:
ALTER PROCEDURE [dbo].[Provider]
(
@strPro varchar(200)
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @SQL varchar(2000)
-- Insert statements for procedure here
SET @SQL = 'SELECT * FROM [db1].[dbo].[table1] '
if @strPro <> 'All People'
BEGIN
SET @SQL = @SQL + ' WHERE [Name] = ''' + @strPro + '''
END
EXEC (@SQL)
END
注意1:如果你想要所有人&#39;你不会需要一个WHERE子句。 ... 注2:您可能需要调整一些单引号...