declare @变量 = 值
我用 select @变量 from 表名 where = 条件 查出来的是变量的值,而不是变量那一列的值。
请问应该怎么做?
------解决方案--------------------
- SQL code
exec('select [email protected]+' from 表名')
------解决方案--------------------
- SQL code
declare @变量 = 值select @变量=字段 from 表名 where = 条件print @变量
------解决方案--------------------
- SQL code
--我估计是动态sqlexec ('select [email protected]+' from 表名 where = 条件')
------解决方案--------------------
exec ('select [email protected]+' from 表名 where = 条件')
------解决方案--------------------
declare @变量 = 值
我用 select @变量 from 表名 where = 条件 查出来的是变量的值,而不是变量那一列的值。
请问应该怎么做?
- SQL code
exec ('select ' + @變量 + ' from 表名 = 條件 ' )
------解决方案--------------------
- SQL code
显然是exec('select [email protected]+' from 表名')
------解决方案--------------------
declare @var type
set @var = value
select @var
例:
declare @var varchar(10)
set @var = 'abcdefg'
select @var
------解决方案--------------------
參照方法
- SQL code
--动态语句语法/******************************************************************************************************************************************************动态语句语法:exec\sp_executesql语法整理人:中国风(Roy)日期:2008.06.06******************************************************************************************************************************************************/动态语句语法:--方法1查询表改为动态select * from sysobjectsexec('select ID,Name from sysobjects')exec sp_executesql N'select ID,Name from sysobjects'--多了一个N为unicode--方法2:字段名,表名,数据库名之类作为变量时,用动态SQL declare @FName varchar(20)set @FName='ID'exec('select [email protected]+' from sysobjects where [email protected]+'=5' )declare @s varchar(1000)set @s=N'select [email protected]+' from sysobjects where [email protected]+'=5'exec sp_executesql @s--会报错declare @s nvarchar(1000)--改为nvarcharset @s=N'select [email protected]+' from sysobjects where [email protected]+'=5'exec sp_executesql @s--成功--方法3:输入参数declare @i int,@s nvarchar(1000)set @i=5exec('select ID,Name from sysobjects where [email protected])set @s='select ID,Name from sysobjects where [email protected]'exec sp_executesql @s,[email protected] int',@i--此处输入参数要加上N--方法4:输出参数declare @i int,@s nvarchar(1000)set @s='select @i=count(1) from sysobjects'--用execexec('declare @i int [email protected]+' select @i')--把整个语句用字符串加起来执行--用sp_executesqlexec sp_executesql @s,[email protected] int output',@i output--此处输出参数要加上Nselect @i--方法5:输入输出--用sp_executesqldeclare @i int,@con int,@s nvarchar(1000)set @i=5select @s='select @con=count(1) from sysobjects where ID>@i'exec sp_executesql @s,[email protected] int output,@i int',@con output ,@i select @con--用execdeclare @i int,@s nvarchar(1000)set @i=5select @s='declare @con int select @con=count(1) from sysobjects where ID>'+rtrim(@i)+' select @con'exec(@s)