3

I am using a dynamic sql i.e.

DECLARE @searchstring VARCHAR(500)
DECLARE @str VARCHAR(MAX)
SELECT @str = 'SELECT * FROM Table1 WHERE ' + @searchstring
EXECUTE @str   

What I need is I want to select one column value from above dynamic sql to pass in a different SP Let's say I need ID column value and pass it to another sp named GetAnotherData @Ids. How can I do that?

4
  • 1
    Chekc this post : stackoverflow.com/questions/803211/… Commented Sep 22, 2013 at 6:31
  • Thanks for the link.. I got an idea that how to proceed. Commented Sep 22, 2013 at 6:38
  • Do you want to select a single row or all rows in the column. Could you clarify that, please? Commented Sep 22, 2013 at 6:39
  • @AlexanderFedorenko All Rows Commented Sep 22, 2013 at 6:40

2 Answers 2

5

well you can go with Alexander Fedorenko example, but if you don't want to create any temp tables, you can use output xml parameter to pass your ids:

declare @stmt nvarchar(max), @Data xml, @searchstring nvarchar(max)

select @stmt = '
    select @Data = (
        select id
        from Table1
        where ' + @searchstring + '
        for xml raw(''Data'')
    )
'

exec sp_executesql
    @stmt = @stmt,
    @params = N'@Data xml output',
    @Data = @Data output

select
    T.C.value('@id', 'int') as id
from @Data.nodes('Data') as T(C)

sql fiddle demo

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

Comments

0

The following example creates a user-defined table type that has one Id column. Further the INSERT @RetIds EXEC(@STR) statement fills the parameter list, and then passes the values to a stored procedure

CREATE TYPE RetIds AS TABLE
 (
  Id int
  )

DECLARE @searchstring varchar(500) = 'AND SearchCol = 1'
DECLARE @str varchar(max)
SELECT @str ='SELECT Id FROM dbo.test6 WHERE 1 = 1 ' + @searchstring

DECLARE @RetIds AS RetIds
INSERT @RetIds
EXEC(@str)
EXEC dbo.ExecIds @RetIds

See demo on SQLFiddle

4 Comments

As far as I know there is no way to pass the data set to a stored procedure without creating a temp table. No magic bullet here;)...
@AlexanderFedorenko there's a way with xml parameter :) don't know if OP'll like it
Ok. This means we can pass xml type to a stored procedure. It's fun, a little bit awkward, but interesting;)catch +1 Roman
@AlexanderFedorenko thanks, yes, it is a bit awkward that's why not all my collegaues use it :) but I personally like xml support in SQL Server, it often helps me

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.