0

I have a stored procedure with the following dynamic query

ALTER PROCEDURE [dbo].[Del_AE_Update] 
      @uid nvarchar(MAX)
AS
BEGIN
    Declare @AEname varchar(MAX);
    Declare @sqlquery varchar(MAX);

    Set @sqlquery = ('Select name FROM OPENQUERY(CRM_MYSQL,''Select name From tscrm_prod.user_info where uid='+@uid+''')')  

    Select @sqlquery
END

However I am getting the value in name. I want it to be assigned to @sqlquery because I need to use it in next part of the procedure.

This is how my results look.

name= Dallas-BDD

@sqlquery = 'Select name FROM OPENQUERY...
2
  • So the next step would be to run your openquery. Commented Nov 16, 2015 at 16:31
  • Yes I need to know how to do that exactly. I am totally unaware of doing it syntactically. Commented Nov 16, 2015 at 17:05

1 Answer 1

1

You have to execute the query string (@sqlquery) to be able to get the value of your query. To be able to get the result of a dynamic query into a variable, you need to use sp_executesql with one input and one output parameters.

There are so many examples on the web.

it will look something like this: (This is a simplified version to give you an idea)

DECLARE @ParmDefinition nvarchar(500);
Declare @sqlquery nvarchar(4000);
Declare @name varchar(100);

Set @sqlquery =('Select @name= UserName From tmp_users where userid=@uid') 

    SET @ParmDefinition = N'@uid varchar(max),
        @name nvarchar(25) OUTPUT';
    EXECUTE sp_executesql
        @sqlquery
        ,@ParmDefinition
        ,@uid = 1
        ,@name = @name OUTPUT;
Select @name -- which you will be able to use to continue in your SP
Sign up to request clarification or add additional context in comments.

3 Comments

@Urwish Patel, What I put there needs to be worked on. It was just to give you a push in the right direction. check sp_executesql
I understand that, but I am using this for the first time. And have no idea syntactically how to do it. Been stuck on it for 2 days.
@Urwish Patel, I made some modifications to my answer... which can give you a better idea... I tested it and it worked with a temp table I created.

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.