通过使用这个存储过程,你就可以方便的对数据库中具有一定规则的或者全部表,对这里的字段进行各种操作,具体看示例!
create procedure sp_execsqlondb
(@tablename varchar(50), --表名条件
@columnname varchar(50), --字段条件
@sql nvarchar(4000), --执行的sql
@include_nti char(1) = ’n’) --是否包含text,ntext,image数据类型
as
begin
--variable declaration
--变量定义
declare @strsql nvarchar(4000)
declare @sql2 nvarchar(4000)
declare @stablename varchar(200)
declare @scolumnname varchar(200)
declare @sqltemp nvarchar(4000)
--check whether to include text, ntext, image data types
--检查是否需要包含 text,ntext,image数据类型
set @include_nti = upper(ltrim(rtrim(@include_nti)))
if @include_nti not in (’n’, ’y’)
set @include_nti = ’n’
--construct a cursor to get the list of table/column names according to the @tablename and @columnname parameters.
--创建一个游标来读取表名和列名的列表,这里列表由参数@tablename 和 @columnname 决定
set @strsql = n’declare tabcolcursor cursor for select rtrim(ltrim(su.name)) + ’’.’’ + ltrim(rtrim(so.name)), sc.name from sysobjects so inner join syscolumns sc on so.id = sc.id inner join sysusers su on so.uid = su.uid where so.xtype = ’’u’’ ’
--filter out text/ntext/image data types if it is not included
--假如不包含text/ntext/image数据类型,把他们过滤掉
if @include_nti = ’n’
--in syscolumns sytem table xtype column corresponds to column data type
set @strsql = @strsql + ’ and sc.xtype not in (35, 99, 34) ’
--add the table(s) name i.e. filter if it is supplied
--假如有提供表名参数,把它写入过滤条件中
if @tablename is not null and ltrim(rtrim(@tablename)) <> ’’
begin
set @tablename = replace(@tablename, ’, ’, ’,’)
set @strsql = @strsql + ’ and (so.name like ’’’ + replace(@tablename, ’,’, ’’’ or so.name like ’’’) + ’’’)’
set @sqltemp= ’ and (so.name like ’’’ + replace(@tablename, ’,’, ’’’ or so.name like ’’’) + ’’’)’
end
--add the column(s) name i.e. filter if it is supplied
--假如有提供列名参数,把它写入过滤条件中
if @columnname is not null and ltrim(rtrim(@columnname)) <> ’’
begin
set @columnname = replace(@columnname, ’, ’, ’,’)
set @strsql = @strsql + ’ and (sc.name like ’’’ + replace(@columnname, ’,’, ’’’ or sc.name like ’’’) + ’’’)’
end
--execute the constructed "cursor declaration" string
--执行定义游标的sql语句
execute sp_executesql @strsql
if @@error > 0
begin
print ’error while declaring the cursor. please check out the parameters supplied to the procedure’
return -1
end
--database transaction.
--标记一个显式本地事务的起始点
begin transaction gdatabasetrans
--open the cursor
--打开游标
open tabcolcursor
--fetch te table, column names to variables
--用游标取出标名、列名对应到参数
fetch next from tabcolcursor
into @stablename, @scolumnname
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器