Sql 如何根据动态查询结果的值执行动态查询
我有以下SP,当Sql 如何根据动态查询结果的值执行动态查询,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我有以下SP,当query 2的值=0或null时,我想执行query 3,并想返回query 1和query 2/query 3 当我执行SP时,我在@val1=50中有一个值,但它仍然在if循环中,我只想返回@val,@val1,但我得到了5个值 exec usp_GetDefaultValue 'HQP','home','ConDefault','12345' 结果: HQP:0//query 1 HQP:50//query 2@val:0@val1:0有人能帮我吗 ALTER PROC
query 2的值=0
或null
时,我想执行query 3
,并想返回query 1和query 2/query 3
当我执行SP时,我在@val1=50
中有一个值,但它仍然在if循环中,我只想返回@val
,@val1
,但我得到了5个值
exec usp_GetDefaultValue 'HQP','home','ConDefault','12345'
结果:
HQP:0//query 1 HQP:50//query 2@val:0@val1:0有人能帮我吗
ALTER PROCEDURE [dbo].[usp_GetDefaultValue]
@Service varchar(20), @LOB varchar(10), @Scenario varchar(20), @Num varchar(10)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @val as int
DECLARE @val1 as int
DECLARE @Value AS NVARCHAR(MAX)
DECLARE @DefValue AS NVARCHAR(MAX)
set @Value = 'SELECT ' + @Service + ' from PDetail where LOB = ''' + @LOB + ''' and Scenario = ''' + @Scenario + ''' and Number = ''' + @Num + ''' ' -- query 1
set @DefValue = 'SELECT ' + @Service + ' from PDetail where LOB = ''' + @LOB + ''' and Scenario = ''none'' and Number =''none'' and pid = 1' -- query 2
exec @val = sp_executesql @Value
exec @val1 = sp_executesql @DefValue
if (@val1 = 0 or @val1 = null)
begin
set @DefValue = null
set @DefValue = 'SELECT ' + @Service + ' from PDetail where LOB = ''' + @LOB + ''' and Scenario = ''none'' and pid = 2' -- query 3
exec @val1 = sp_executesql @DefValue
end
select @val,@val1 -- want to return only two values
END
我建议你换衣服
if (@val1 = 0 or @val1 = null)
到
请记住,这是SQL,检查null的正确方法是使用is null
您遇到了什么问题?请具体说明每当我看到这样的问题时,我总是认为主要问题是糟糕的表设计/结构。@Jeffrey Wieder:更新了我遇到的问题。请阅读Erland Sommarskog的。您的代码存在SQL注入的风险。
if (@val1 IS NULL or @val1 = 0)