通過使用這個存儲過程,你就可以方便的對數據庫中具有一定規則的或者全部表,對這裡的字段進行各種操作,具體看示例!
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, ’,’