MS SQL 在存储过程中怎样执行用变量组合的SQL语句

2024-12-25 01:23:44
推荐回答(2个)
回答1:

创建:
create procedure p_1
as
declare @empcode nvarchar(10)
declare @result nvarchar(20)
begin
set @empcode='1001'
select @result=c_name from employee where empcode=@empcode
print @result
end

执行:exec p_1

回答2:

动态sql拼接,大致上是这样:
declare @empcode nvarchar(10)
declare @sql_text nvarchar(100)
declare @result nvarchar(20)

set @empcode='1001'
set @sql_text='select c_name from employee where empcode='

select @sql_test=@sql_text+'''+@empcode+'''
exec(@sql_test)