怎樣在SQL Server中去除表中不可見字符

2010-08-28 10:54:37來源:西部e網(wǎng)作者:

以下的實例為去除指定表中數(shù)據(jù)類型是VARCHAR,CHAR,NVARCHAR的字段值中的不可見字符。 注釋:此處只去掉前后的不可見字符,不包括中間的字符,而且沒有區(qū)分中文。

在使用前需要指定對應(yīng)要修改的表名,并且需要在對應(yīng)數(shù)據(jù)庫下執(zhí)行;

SET NOCOUNT ON
DECLARE @TblName  VARCHAR(100)
DECLARE @UpdateString NVARCHAR(1000)
DECLARE @SelectString NVARCHAR(1000)
DECLARE @COlName VARCHAR(100)
DECLARE @COUNT  INT
SET @TblName = 'YOURTABLENAME'--指定想要修改的表名
--定義游標(biāo)取出指定表內(nèi)的數(shù)據(jù)類型是VARCHAR,char,nVARCHAR的字段名稱
DECLARE cur_ColName  CURSOR
FOR
SELECT col.name
FROM syscolumns AS col
inner join sysobjects  AS obj  ON col.ID = obj.ID
INNER join systypes  AS typ  ON col.xtype = typ.xtype
WHERE obj.xtype ='U'
AND obj.name = @TblName
AND typ.name IN ('VARCHAR','CHAR','NVARCHAR','NCHAR')
FOR READ ONLY
--打開游標(biāo)
OPEN cur_ColName
FETCH NEXT FROM cur_ColName INTO @ColName
IF @@FETCH_STATUS<>0
BEGIN
PRINT '沒有對應(yīng)表或字段,
'PRINT '請確認當(dāng)前數(shù)據(jù)庫內(nèi)有' + @TblName + '表,
' PRINT '或該表內(nèi)有VARCHAR、CHAR、NVARCHAR、NCHAR類型的字段!
' GOTO LABCLOSE
END--循環(huán)修改
WHILE @@FETCH_STATUS=0
BEGIN
--拼修改字符串
--去掉左邊的不可見字符
SET @SelectString = 'SELECT @COU=COUNT(*)   
FROM ' + @TblName +'  
WHERE ASCII(LEFT(' + @ColName +',1))<32
AND '+ @ColName + ' IS NOT NULL'
EXEC sp_executesql @SelectString,N'@COU INT OUTPUT',
@COUNT OUTPUT WHILE @COUNT>0
BEGIN
SET @UpdateString = 
' UPDATE ' + @TblName + 
' SET ' + @ColName + '=RIGHT(' + @ColName + ',LEN(' + @ColName + ')-1)  
WHERE ASCII(LEFT(' + @ColName + ',1))<32  
AND ' + @ColName + ' IS NOT NULL'
EXEC sp_executesql @UpdateString
EXEC sp_executesql @SelectString,N'@COU INT OUTPUT',@COUNT OUTPUT
END
--去掉右邊的不可見字符 SET @SelectString = 'SELECT @COU=COUNT(*)   
FROM ' + @TblName +'  
WHERE ASCII(RIGHT(' + @ColName +',1))<32  
AND '+ @ColName + ' IS NOT NULL'
EXEC sp_executesql @SelectString,N'@COU INT OUTPUT',
@COUNT OUTPUT WHILE @COUNT>0
BEGIN
SET @UpdateString =   ' UPDATE ' + @TblName +   ' SET '
+ @ColName + '=LEFT(' + @ColName + ',LEN(' + @ColName + ')-1)  
WHERE ASCII(RIGHT(' + @ColName + ',1))<32  
AND ' + @ColName + ' IS NOT NULL'
EXEC SP_EXECUTESQL @UpdateString
EXEC sp_executesql @SelectString,N'@COU INT OUTPUT',
@COUNT OUTPUT
END
PRINT 'column: ' + @ColName + '---ok'
FETCH NEXT FROM cur_ColName INTO @ColName
END
--關(guān)閉、釋放游標(biāo)LABCLOSE: CLOSE cur_ColName
DEALLOCATE cur_ColName

關(guān)鍵詞:SQLServer

贊助商鏈接: