TSQL - 导出为多个文本文件

时间:2017-02-25 05:53:36

标签: sql-server tsql

所以我需要将表中的ID号导出为多个文本文件(300个长度),我正在尝试使用BCP来实现这一点并尝试使用以下内容:

DECLARE  @First             int
        ,@Last              int
        ,@Range             INT
        ,@docName           NVARCHAR(20)
        ,@SQLCommand        NVARCHAR(MAX)
SELECT @First   = MIN(CandidateID)  FROM tblCandidate
SELECT @Last    = MAX(CandidateID)  FROM tblCandidate
SELECT @DocName = 1
SELECT @Range   = 300
WHILE @First <= @Last
BEGIN
    SELECT @docName = 1
    SET @SQLCommand = 'EXEC xp_cmdshell ''bcp "SELECT CandidateID FROM db1.dbo.tblCandidate WHERE [CandidateID] = ''''' 
                    + 'BETEEN ' +  CAST(@First AS NVARCHAR) + ' AND ' + CAST(@Range AS NVARCHAR) 
                    + '''''" queryout "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\test\' + CAST(@DocName AS NVARCHAR(20)) + '.txt" -T -c -t,''' 
    PRINT @SQLCommand
    EXEC (@SQLCommand)
    SET @First = @First + 300
    SET @Range = @Range + 300
    SET @DocName = @DocName + 1
END

但是我一直收到以下错误:

Starting copy...
SQLState = 22005, NativeError = 245
Error = [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the varchar value 'BETEEN 1 AND 300' to data type int.
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC Driver 13 for SQL Server]Unable to resolve column level collations
NULL
BCP copy out failed

我在这里做错了什么想法?

----编辑:----------------------------------------- ----------------------------

将SQLCommand更改为:

SET @SQLCommand = 'EXEC xp_cmdshell ''bcp "SELECT CandidateID FROM TRIS_Aspen.dbo.tblCandidate WHERE [CandidateID] ''''' 
                + 'BETWEEN ' +  CAST(@First AS NVARCHAR) + ' AND ' + CAST(@Range AS NVARCHAR) 
                + '''''" queryout "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\test\"' + CAST(@DocName AS NVARCHAR(20)) + '.txt" -T -c -t,''' 

我现在收到以下错误:

SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC Driver 13 for SQL Server]Unable to open BCP host data-file
NULL

2 个答案:

答案 0 :(得分:2)

两个错别字:

  • [CandidateID] = - 在此列中使用BETWEEN时丢失等于
  • BETEEN - 更改为BETWEEN

试试这个:

SET @SQLCommand = 'EXEC xp_cmdshell ''bcp "SELECT CandidateID FROM TRIS_Aspen.dbo.tblCandidate WHERE [CandidateID] ''''' 
                    + 'BETWEEN ' +  CAST(@First AS NVARCHAR) + ' AND ' + CAST(@Range AS NVARCHAR) 
                    + '''''" queryout "C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\test\' + CAST(@DocName AS NVARCHAR(20)) + '.txt" -T -c -t,'''

答案 1 :(得分:1)

between命令只需要看起来像

[CandidateID] BETWEEN 1 AND 300

您的代码正在生成

[CandidateID] ''' BETWEEN 1 AND 300

松开不必要的引号