1 :普通SQL语句可以用Exec执行
eg: Select * from tableName
Exec('select * from tableName')
Exec sp_executesql N'select * from tableName' -- 请注意字符串前一定要加N
2:字段名,表名,数据库名之类作为变量时,必须用动态SQL
eg:
declare @fname varchar(20)
set @fname = 'FiledName'
Select @fname from tableName -- 错误,不会提示错误,但结果为固定值FiledName,并非所要。
Exec('select ' + @fname + ' from tableName') -- 请注意 加号前后的 单引号的边上加空格
当然将字符串改成变量的形式也可
declare @fname varchar(20)
set @fname = 'FiledName' --设置字段名
declare @s varchar(1000)
set @s = 'select ' + @fname + ' from tableName'
Exec(@s) -- 成功
exec sp_executesql @s -- 此句会报错
declare @s Nvarchar(1000) -- 注意此处改为nvarchar(1000)
set @s = 'select ' + @fname + ' from tableName'
Exec(@s) -- 成功
exec sp_executesql @s -- 此句正确
3. 输出参数
declare @num int,
@sqls nvarchar(4000)
set @sqls='select count(*) from tableName'
exec(@sqls)
--如何将exec执行结果放入变量中?
declare @num int,
@sqls nvarchar(4000)
set @sqls='select @a=count(*) from tableName '
exec sp_executesql @sqls,N'@a int output',@num output
select @num
例:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
-- =============================================
-- Create date: 2008.03.22
-- Description: 验证用户存在性
-- =============================================
ALTER PROCEDURE [dbo].[Proc_CheckUser]
@CheckName varchar (50) ,
@Result varchar(20) OUtPUT
AS
BEGIN
SET NOCOUNT ON;
declare @WhereStr varchar (500), @SQLStr Nvarchar(4000),@re bit
IF(left(@CheckName,5)='95002' and isnumeric(@CheckName)=1) SET @CheckName=substring(@CheckName,6,len(@CheckName))-- 登陆号码前+95002
IF(isnumeric(@CheckName)=1) SET @WhereStr='UID = '''+@CheckName+''''-- 登陆号码前+95002
IF((left(@CheckName,2)='13' OR left(@CheckName,2)='15' and len(@CheckName)=11) and isnumeric(@CheckName)=1) SET @WhereStr='Phone = '''+@CheckName+''''-- 手机号码
IF(left(@CheckName,1)='0' and isnumeric(@CheckName)=1 and (len(@CheckName) between 10 and 13)) SET @WhereStr='TelePhone = '''+@CheckName+'''' -- 固定电话
IF(Charindex('@',@CheckName)>0 and Charindex('.',@CheckName)>0 and isnumeric(@CheckName)=0) SET @WhereStr='Email = '''+@CheckName+'''' -- email
SET @SQLStr = 'set @re=case when exists(select 0 from Passport_Account where '+@WhereStr+' and 1=1) then 1 else 0 end'
exec sp_executesql @SQLStr,N'@re bit output,@WhereStr varchar(500)',@re output,@WhereStr
if @re=1
BEGIN
SET @SQLStr=N'select @Result=UID from Passport_Account where '+@WhereStr+' and 1=1'
exec sp_executesql @SQLStr ,N'@Result varchar(20) output,@WhereStr varchar(500)',@Result output,@WhereStr
SET @Result='1'+@Result
Print @Result
END
ELSE
BEGIN
SET @Result=0
print 0
END
END