去除指定表中数据类型是VARCHAR,CHAR,NVARCHAR的字段值中的不可见字符
--作用:去除指定表中数据类型是VARCHAR,CHAR,NVARCHAR的字段值中的不可见字符
--注意:此处只去掉前后的不可见字符,不包括中间的字符,而且没有区分中文
--有兴趣的可以自己加个判别的中文,其实也很简单的,就是限定一个字符的范围就可以了
--日期:2004-11-04
--作者:ICERIVER
--注意:使用前请指定对应要修改的表名,并且需要在对应数据库下执行;
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'--指定想要修改的表名
--定义游标取出指定表内的数据类型是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
--打开游标
OPEN cur_ColName
FETCH NEXT FROM cur_ColName INTO @ColName
IF @@FETCH_STATUS<>0
BEGIN
PRINT '没有对应表或字段,'
PRINT '请确认当前数据库内有' + @TblName + '表,'
PRINT '或该表内有VARCHAR、CHAR、NVARCHAR、NCHAR类型的字段!'
GOTO LABCLOSE
END
--循环修改
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
--关闭、释放游标
LABCLOSE: CLOSE cur_ColName
DEALLOCATE cur_ColName
欢迎访问最专业的网吧论坛,无盘论坛,网吧经营,网咖管理,网吧专业论坛
https://bbs.txwb.com
关注天下网吧微信/下载天下网吧APP/天下网吧小程序,一起来超精彩
|
本文来源:vczx 作者:佚名