从单个存储过程中的多个 select 语句中选择指定的查询
Selecting specified query from multiple select statement inside a single stored procedure
大家好!
我到处搜索如何在单个存储过程中使用 if-else 语句获取指定的查询,但仍然没有找到如何实现这些功能的方法。
这是T-Sql
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[getHistoryList]
@documentNo varchar(150)=null,
@material varchar(150)=null,
@action varchar(10)=null
as
declare @query nvarchar(max);
if (@action = null)
begin
set @query = 'select top 50 * from s_HistoryList order by documentDate desc'
exec sp_executesql @statement=@query
end
else if (@action = 'search')
begin
set @query = 'select * from s_HistoryList where documentNo like %'+@documentNo+'% or materialName like %'+@material+'%'
exec sp_executesql @statement=@query
end
go
调用 exec 命令时,只有 return 个命令成功完成,而不是 value/table 个所选命令。由于 @action 为 null,它应该 return 以下查询,当 @action 提供值时,它应该 return 第二个查询。
删除 if-else 语句后,它 return 是第一个查询,但无法访问第二个查询。
我看到了这个方法here。
谢谢你,我很感激这个 post 能得到的任何帮助。
您需要将变量打印为变量@action 的值。
例如:
begin
set @query = 'select * from s_HistoryList where documentNo like %'+@documentNo+'% or materialName like %'+@material+'%'
exec sp_executesql @statement=@query
print 'Below is the value of @action'
print @action
end
A point i would make is that NULL comparison wouldnt work with = sign.
if (@action = null) to be changed to
if (@action IS NULL)
大家好!
我到处搜索如何在单个存储过程中使用 if-else 语句获取指定的查询,但仍然没有找到如何实现这些功能的方法。
这是T-Sql
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[getHistoryList]
@documentNo varchar(150)=null,
@material varchar(150)=null,
@action varchar(10)=null
as
declare @query nvarchar(max);
if (@action = null)
begin
set @query = 'select top 50 * from s_HistoryList order by documentDate desc'
exec sp_executesql @statement=@query
end
else if (@action = 'search')
begin
set @query = 'select * from s_HistoryList where documentNo like %'+@documentNo+'% or materialName like %'+@material+'%'
exec sp_executesql @statement=@query
end
go
调用 exec 命令时,只有 return 个命令成功完成,而不是 value/table 个所选命令。由于 @action 为 null,它应该 return 以下查询,当 @action 提供值时,它应该 return 第二个查询。
删除 if-else 语句后,它 return 是第一个查询,但无法访问第二个查询。
我看到了这个方法here。
谢谢你,我很感激这个 post 能得到的任何帮助。
您需要将变量打印为变量@action 的值。 例如:
begin
set @query = 'select * from s_HistoryList where documentNo like %'+@documentNo+'% or materialName like %'+@material+'%'
exec sp_executesql @statement=@query
print 'Below is the value of @action'
print @action
end
A point i would make is that NULL comparison wouldnt work with = sign.
if (@action = null) to be changed to
if (@action IS NULL)