我想将变量设置为使用查询外部的动态查询生成的值。
我尝试了sp_executesql
概念,但这对我没有帮助,因为我在动态查询中使用了参数值。
有没有可能解决这个问题?
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
答案 0 :(得分:2)
希望此代码适合您。
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]不确定我不知道专栏名称
答案 1 :(得分:1)
在动态sql中使用输出参数,如图所示here 另见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