动态SQL语句

2016-01-29 16:46 2 1 收藏

动态SQL语句,动态SQL语句

【 tulaoshi.com - SQLServer 】

1:普通SQL语句可以用Exec执行
eg:   Select * from tableName
      Exec('select * from tableName')
      sp_executesql N'select * from tableName'    -- 请注意字符串前一定要加N

2:字段名,表名,数据库名之类作为变量时,必须用动态SQL
eg:  
declare @fname varchar(20)
set @fname = '[name]'
Select @fname from sysobjects                     -- 错误
Exec('select ' + @fname + ' from sysobjects')     -- 请注意 加号前后的 单引号的边上要加空格
exec sp_executesql N' select ' + @fname + ' from sysobjects'
当然将字符串改成变量的形式也可
    declare @s varchar(1000)
    set @s = 'select ' + @fname + ' from sysobjects'
    Exec(@s)                -- 成功
    exec sp_executesql @s   -- 此句会报错

    declare @s Nvarchar(1000)  -- 注意此处改为nvarchar(1000)
    set @s = 'select ' + @fname + ' from sysobjects'
    Exec(@s)                -- 成功   
    exec sp_executesql @s   -- 此句正确,

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/sqlserver/)

3: 输出参数
eg:
declare @num,
        @sqls
set @sqls='select count(*) from  ' + @servername + '.a.dbo.b'
exec(@sqls)
我如何能将exec执行的结果存入变量@num中

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/sqlserver/)

declare @num int,
        @sqls nvarchar(4000)
set @sqls='select @a=count(*) from '+@servername+'.a.dbo.b'
exec sp_executesql @sqls,N'@a int output',@num output
select @num

来源:https://www.tulaoshi.com/n/20160129/1499508.html

延伸阅读
标签: SQLServer
说明:查询从第30条到第40条的记录数   SQL:select top 10 * from temp where id not in (select top 30 id from temp order by id asc) order by id asc   说明:复制表(只复制结构,源表名:a 新表名:b)    SQL: select * into b from a where 1<1     说明:拷贝表(拷贝数据,源表名:a...
说明:复制表(只复制结构,源表名:a 新表名:b) select * into b from a where 11 说明:拷贝表(拷贝数据,源表名:a 目标表名:b) insert into b(a, b, c) select d,e,f from b; 说明:显示文章、提交人和最后回复时间 select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title...
1.调整内存 sp_configure 'show advanced options',1 GO RECONFIGURE Go sp_configure 'awe enabled', 1 GO RECONFIGURE Go sp_configure 'min server memory',1024 Go sp_configure 'max server memory',3072 GO RECONFIGURE Go PS: OS需要打开AWE 即在boot.ini里 添加 /3G 或者 /PAE (企业版)才能支持4G以上内存! 2.关...
标签: SQLServer
为了大家更容易理解我举出的SQL语句,本文假定已经建立了一个学生成绩管理数据库,全文均以学生成绩的管理为例来描述。 1.在查询结果中显示列名: a.用as关键字:select name as '姓名' from students order by age b.直接表示:select name '姓名' from students order by age 2.精确查找: a.用in限定范围:select *...
都是一些精典实用的常用语句. MYSQL显示数据库或表: 以下为引用的内容: show databases;//然后可以use database_name; show tables; MYSQL更改表名: alter table table_name rename new_t; MYSQL添加列 : alter table table_name add column c_n column attributes; MYSQL删除列: alter table tabl...

经验教程

427

收藏

44

精华推荐

SQL 查询语句积累

SQL 查询语句积累

Tiramisu楼

SQL2005 高效分页sql语句

SQL2005 高效分页sql语句

小亮xiaopin

SQL高手篇:精妙SQL语句介绍

SQL高手篇:精妙SQL语句介绍

疯子东o0O

热门标签

SQL
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部