惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

有赞技术团队
有赞技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
IT之家
IT之家
博客园 - 【当耐特】
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
MyScale Blog
MyScale Blog
WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Hugging Face - Blog
Hugging Face - Blog
I
InfoQ
B
Blog RSS Feed
腾讯CDC
云风的 BLOG
云风的 BLOG
N
Netflix TechBlog - Medium
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
雷峰网
雷峰网
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
D
DataBreaches.Net
The Cloudflare Blog
V
V2EX
S
SegmentFault 最新的问题

博客园 - noviceliu

Access to the path '' is denied.解决方案 搭建网站IIS目录权限设置说明 ASP.NET获取当前网址url的各种属性 GridView绑定技巧终结者 类型初始值设定项引发异常处理办法 string和byte[]的转换 Oracle数据库的三种标准的备份方法 Coin Slider jQuery插件使用方法 ckeditor 在C#中使用 ASP.NET PostedFile.ContentType所有类型对应值 用户控件.ascx与网页.aspx交互的几种方法 Microsoft.VisualBasic.PowerPacks相关错误解决办法 MySQL数据库与MS SQL Server不同之处的表现 ERROR [IM002] [Microsoft][ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序 - noviceliu 未能加载文件或程序集“SQLServerDAL”或它的某一个依赖项,系统找不到指定的文件-解决办法 - noviceliu - 博客园 执行动态SQL列明无效的解决办法 GROUP by总结 EXECUTE后的事务计数指出缺少了COMMIT或ROLLBACK TRANSACTION语句。原计数=0,当前计数=1。 SQL Server 2005存储过程调试
动态sql语句基本语法
noviceliu · 2010-01-28 · via 博客园 - noviceliu

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