0

I want to set a variable to the value generated using the dynamic query outside the query.

I tried the sp_executesql concept, but this does not help me because I am using the parameter value in the dynamic query.

Are there any possibilities to fix this issue?

CREATE PROCEDURE [dbo].[SP_test_proc] 
    @id int = null, 
    @deptId int = null
As
BEGIN
    DECLARE @Condition VARCHAR(MAX),@Query NVARCHAR(MAX)

    SET @Condition= 'Where Id = '@id + case when @deptid is null then '' else @deptid End

    SET @Query = 'Declare @Name varchar(100)
                  Set @Name = Select name from student '+ @Condition

    SELECT * 
    FROM personal 
    WHERE name = @Name
END
1

2 Answers 2

1

Use output parameter in dynamic sql as shown here Also see this Try this :

DECLARE @Condition VARCHAR(MAX),@Query NVARCHAR(MAX)

    SET @Condition= 'Where Id = '@id + case when @deptid is null then '' else @deptid End
    Declare @Name varchar(100),@nameval varchar(100),@paramdef varchar(100)

    SET @Query = '
                  Select @Name = name from student '+ @Condition

    set @paramdef=N'@Name varhcar(20) OUTPUT'

    execute sp_executesql @Query,@paramdef,@Name=@nameval Output
    SELECT * 
    FROM personal 
    WHERE name = @nameval
Sign up to request clarification or add additional context in comments.

2 Comments

how to do it for more than one parameter?
Then in paramdef, add comma separated output variable definitions and similarly pass those variables as comma separated parameters in sp_executesql procedure
1

Hope this code will work for you.

CREATE PROCEDURE [dbo].[SP_test_proc] 
@id int = null, 
@deptId int = null
As
BEGIN
DECLARE @Condition VARCHAR(MAX),@Query NVARCHAR(MAX)

SET @Condition= 'Where Id = ' + @id + ' And [Deptid] = ' + ISNULL(@deptid,'')

SET @Query = 'SELECT * FROM personal WHERE name IN ( SELECT name FROM student ' +  @Condition + ')'
EXEC @Query
END

[Deptid] is not sure I don't know column name

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.