1

I have below SP and want to excute query 3 when the value of query 2 = 0 or null and want to return values of query 1 and query 2/query 3

When I execute the SP I have a value in @val1 = 50 but still it is going inside the if loop and i want to return only @val, @val1 but i am getting 5 values

exec usp_GetDefaultValue 'HQP','home','ConDefault','12345'

Results:

HQP: 0 // query 1 HQP: 50 //query 2 @val: 0 @val1: 0 can anybody help me in this

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
4
  • What is the problem you are having? Please be specific Commented Jul 6, 2015 at 20:23
  • Whenever I see questions like this I always think the main problem is a poor table design/structure. Commented Jul 6, 2015 at 20:33
  • @ Jeffrey Wieder: updated the problem i am having. Commented Jul 6, 2015 at 20:49
  • Please read Erland Sommarskog's The Curse and Blessings of Dynamic SQL. Your code is at risk for SQL injection. Commented Jul 7, 2015 at 0:00

1 Answer 1

2

I suggest that you change

  if (@val1 = 0 or @val1 = null) 

to

  if (@val1 IS NULL or @val1 = 0) 

Remember that this is SQL, the proper way to check for null is with IS NULL

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.