question

taj avatar image
taj asked

How to assign Stored Procedure having dynamic query to a variable in SQL Server

**actual Oracle Code** function USF_CONFIG(p_config in varchar2, p_valType in varchar) return varchar AS config_value varchar(500); BEGIN EXECUTE IMMEDIATE ' select '||p_valType||'_VALUE from TBL_CONFIGS where CONFIG=''' || p_config || '''' into config_value; RETURN config_value; END; **Migrated SQL Server code** CREATE PROCEDURE usp_GetConfig (@p_Config varchar(4000), @p_ValType varchar(500)) AS BEGIN declare @v_SqlStr Nvarchar(100) set @v_SqlStr = ' select '+@p_ValType+'_Value from tbl_Configs where Config =''' +@p_Config+ '''' execute sp_executesql @v_SqlStr end **Testing code** declare @op varchar(100)='' exec usp_GetConfig 10,'na' 1]print @op 2]select @op 3]if @op='kka' print 'hi' else print 'bye' **here 1 2 and 3 not giving expected output.. is there any other way to write code**
sql-server-2008
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Kev Riley avatar image
Kev Riley answered
You are not setting the value of @siteId to anything in the executed sql: set @v_SqlStr = ' select @siteId ='+@p_ValType+'me from dev_common.dbo.ok where id=''' +@p_Config+ ''''
9 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

taj avatar image taj commented ·
sir what about"exec uspEAQ_Get 10,'na',@op OUTPUT print @op" i need SP's result to use further in other variables
0 Likes 0 ·
Kev Riley avatar image Kev Riley ♦♦ commented ·
There's no need to change that part - you are simply not setting the variable to anything
0 Likes 0 ·
taj avatar image taj commented ·
can i write this SP without 'out' parameter i.e. @p_result varchar(max)output if yes how is it and how to assign that result of procedure to variable which don't have out parameter
0 Likes 0 ·
Kev Riley avatar image Kev Riley ♦♦ commented ·
Yes you can capture the output of a procedure into a table - using the insert into...exec... See the first example here : https://msdn.microsoft.com/en-us/library/ms174335.aspx#OtherTables
0 Likes 0 ·
taj avatar image taj commented ·
sir please check edited code
0 Likes 0 ·
Show more comments

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.