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
sp_prefix for your stored procedures. Microsoft has reserved that prefix for its own use (see Naming Stored Procedures), and you do run the risk of a name clash sometime in the future. It's also bad for your stored procedure performance. It's best to just simply avoidsp_and use something else as a prefix - or no prefix at all!