简单的查询问题,在线等。。。
declare @tablename as varchar(20)
select @tablename = (select top 1 tablename from user_temp )
这样就给@tablename赋值了,
但是如果SQL语句里有变量的话,如何做能把返回值赋给变量呢,
如:select top 1 tablename from user_temp where type= '条件 '
------解决方案--------------------你這裡沒有必要使用動態SQL語句
declare @username as varchar(20)
declare @tablename as varchar(20)
set @username= 'bccu '
select top 1 @tablename =tablename from userinfo where username=@username
select @tablename
------解决方案--------------------declare @sql as varchar(100)
declare @username as varchar(20)
declare @tablename as varchar(20)
set @username= 'bccu '
set @sql = 'select top 1 @tablename =tablename from userinfo where username= ' ' '+@username+ ' ' ' '
exec sp_executesql @sql,N '@tablename varchar(20) output ',@tablename output
select @tablename
------解决方案--------------------declare @sql as Nvarchar(100)
declare @username as varchar(20)
declare @tablename as varchar(20)
set @username= 'bccu '
set @sql = N 'select top 1 @tablename =tablename from userinfo where username= ' ' '+@username+ ' ' ' '
exe sp_executesql @sql,N '@tablename varchar(20) output ',@tablename output
select @tablename