动态sql语句基本语法
1 :普通SQL语句可以用Exec执行
例: Select * from tableName
Exec('select * from tableName')
Exec sp_executesql N'select * from tableName' -- 请注意字符串前一定要加N
2:字段名,表名,数据库名之类作为变量时,必须用动态SQL
错误: 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) -- 成功
相关文档:
【转】http://space.cnblogs.com/group/topic/33473/
http://www.cnblogs.com/ghd258/archive/2005/10/24/260836.html
如果在SQL Server 里需要定时或者每隔一段时间执行某个存储过程或3200字符以内的SQL语句时,可以用管理->SQL Server代理->作业来实现。
1、管理->SQL Server代 ......
编写一个储存过程usp_GetSortedShippers,它接收Northwind数据库中Shippers表的一个列名称作为其中一个输入(@colname),并从该表返回按输入的列名排序的行。另一个输入(@sortdir)表示排序的方向,‘A’表示按升顺排序,‘D’表示按降序排序。编写该存储过程时要注意它的性能,即,尽可能的使用索引( ......
方法一、尽量使用复杂的SQL来代替简单的一堆 SQL.
同样的事务,一个复杂的SQL完成的效率高于一堆简单SQL完成的效率。有多个查询时,要善于使用JOIN。
oRs=oConn.Execute("SELECT * from Books")
while not oRs.Eof
strSQL = "SELECT * from Authors WHERE AuthorID="&oRs("AuthorID") oRs2=oConn.Execute(strSQ ......
Table-Naming Standards
Table-naming standards, as well as any standard within a business, are critical to
maintaining control. After studying the tables and data in the previous sections, you
probably noticed that each table’s suffix is _TBL. This is a naming standard selected
for use, suc ......
假如你写过很多程序,你可能偶尔会碰到要确定字符或字符窜串否包含在一段文字中,在这篇文章中,我将讨论使用CHARINDEX和PATINDEX函数来搜索文字列和字符串。我将告诉你这两个函数是如何运转的,解释他们的区别。同时提供一些例子,通过这些例子,你可以可以考虑使用这两个函数来解决很多不同的字符搜索的问题。
&nb ......