0

I am trying to implement a nested query with a dynamic query.

I have tried something like this:

SET @str = 'Select @GRP= ' + @Field +' 
           from Hist_Tab 
           Where TerminalID in (Select id from newtab where lease='+@Lease +')';

exec sp_executesql @query=@str,

@params= N' @GRP Numeric(15,2) Ouptut',
@GRP=@GRP Output

but it seems I can't implement the nested queries this way ...

Any suggestion??

Thanks in advance

3
  • 1
    Why does it seem I can't implement nested queries this way - do you get an error? If so: what is that error?! Please post the full, complete error message so we might be able to actually understand what's happening.... Commented Jul 9, 2012 at 13:19
  • Can you tell us what @str contains after its assigned Commented Jul 9, 2012 at 14:19
  • I get that @Field must be a varchar but what is the datatype of @Lease? Commented Jul 9, 2012 at 14:21

1 Answer 1

1

for any local variable passed in you need to make sure that you add additional '' on each side so that the dynamic statement ends up with the equivalent of this while being executed: where lease = 'value of @Lease' the way you have it written is is turning that into: where lease = value of @Lease

will throw an error because the varchar value being compared to lease is missing the single quotes.

try this:

SET @str = 'Select @GRP= ' + @Field +' 
           from Hist_Tab 
           Where TerminalID in (Select id from newtab where lease='''+@Lease +''')';

exec sp_executesql @query=@str,

@params= N' @GRP Numeric(15,2) Ouptut',
@GRP=@GRP Output
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.