SQL Server表中某些字段含有水平制表符、换行符、回车符、反斜杠的解决办法

DECLARE @TableName VARCHAR(50);

SET @TableName = 'Buzzreader_Data_Union';

--系统表syscolumns中xtype = 61表示是日期字段,除了日期字段,其它都可以原样输出
--char(9)  水平制表符
--char(10) 换行键
--char(13) 回车键

DECLARE @datastr2 VARCHAR(MAX);
SELECT  @datastr2 = ISNULL(@datastr2 + ',', '')
        + CASE WHEN b.xtype = 61 THEN '[' + b.name + '] AS [' + b.name + ']'
               ELSE 'replace(replace(replace(replace([' + b.name
                    + '],''\'',''\\''),CHAR(9),''''),CHAR(10),''''),CHAR(13),'''') AS ['
                    + b.name + ']'
          END
FROM    sys.tables a
        JOIN sys.syscolumns b ON a.object_id = b.id
WHERE   a.name = @TableName;

SET @datastr2 = 'SELECT '+@datastr2 + ' FROM ' + @TableName

EXEC master.dbo.PrintLongText @datastr2

EXEC master..xp_cmdshell 'BCP "@datastr2 库名.架构名.表名" queryout 路径\表名.txt -c -t "\t" -T'

你可能感兴趣的:(SQL,Server)