当前位置:首页 > 网络编程 > 数据库 > SQL Server > SQLServer编写存储过程小工具(三)

SQLServer编写存储过程小工具(三)

点击次数:32 次 发布日期:2008-11-21 22:44:12 作者:源代码网
源代码网推荐

源代码网整理以下SQLServer编写存储过程小工具
功能:为给定表创建Update存储过程
语法:sp_GenUpdate<TableName>,<PrimaryKey>,<StoredProcedureName>
以northwind数据库为例
sp_GenUpdate"Employees","EmployeeID","UPD_Employees"

源代码网整理以下注释:如果您在Master系统数据库中创建该过程,那您就可以在您服务器上所有的数据库中使用该过程。

源代码网整理以下


源代码网整理以下/*===========================================================*/
CREATEproceduresp_GenUpdate
@TableNamevarchar(130),
@PrimaryKeyvarchar(130),
@ProcedureNamevarchar(130)
as
setnocounton

源代码网整理以下
declare@maxcolint,
@TableIDint
"knowsky.com
set@TableID=object_id(@TableName)

源代码网整理以下
select@MaxCol=max(colorder)
fromsyscolumns
whereid=@TableID

源代码网整理以下
select"CreateProcedure"+rtrim(@ProcedureName)astype,0ascolorderinto#TempProc
union
selectconvert(char(35),"@"+syscolumns.name)
+rtrim(systypes.name)
+casewhenrtrim(systypes.name)in("binary","char","nchar","nvarchar","varbinary","varchar")then"("+rtrim(convert(char(4),syscolumns.length))+")"
whenrtrim(systypes.name)notin("binary","char","nchar","nvarchar","varbinary","varchar")then""
end
+casewhencolorder<@maxcolthen","
whencolorder=@maxcolthen""
end
astype,
colorder
fromsyscolumns
joinsystypesonsyscolumns.xtype=systypes.xtype
whereid=@TableIDandsystypes.name<>"sysname"
union
select"AS",@maxcol+1ascolorder
union
select"UPDATE"+@TableName,@maxcol+2ascolorder
union
select"SET",@maxcol+3ascolorder
union
selectsyscolumns.name+"=@"+syscolumns.name
+casewhencolorder<@maxcolthen","
whencolorder=@maxcolthen""
end
astype,
colorder+@maxcol+3ascolorder
fromsyscolumns
joinsystypesonsyscolumns.xtype=systypes.xtype
whereid=@TableIDandsyscolumns.name<>@PrimaryKeyandsystypes.name<>"sysname"
union
select"WHERE"+@PrimaryKey+"=@"+@PrimaryKey,(2*@maxcol)+4ascolorder
orderbycolorder

源代码网整理以下
selecttypefrom#tempprocorderbycolorder

源代码网整理以下
droptable#tempproc
/*=======源程序结束=========*/

源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华