SQL Server BCP Command not Writing NVARCHAR(MAX) Variable Contents to File

允我心安 提交于 2019-12-12 04:45:45

问题


I'm having issues with SQL Server's BCP. I'm not getting an error message but the command is also not writing anything to the path specified.

Here is my code:

In this scenario, the only variable not accounted for in the code below is @MESSAGE which is a NVARCHAR(MAX) and will take up most of that space so VARCHAR(8000) won't be nearly big enough.

DECLARE @OUTPUT_TABLE VARCHAR(255) = '##temp' + CONVERT(VARCHAR(12), CONVERT(INT, RAND() * 1000000))
DECLARE @RESULT INTEGER
DECLARE @OUTPUT_EXECUTION_COMMAND NVARCHAR(MAX) = 'CREATE TABLE [' + @OUTPUT_TABLE + '] ( CONTENT NVARCHAR(MAX) )

                                                    INSERT INTO [' + @OUTPUT_TABLE + ']
                                                        SELECT @MESSAGE'

EXECUTE SP_EXECUTESQL @OUTPUT_EXECUTION_COMMAND, N'@MESSAGE NVARCHAR(MAX)', @MESSAGE

DECLARE @OUTPUT_FILE_WRITE_COMMAND VARCHAR(1000) = 'BCP ”SELECT CONTENT FROM [' + @OUTPUT_TABLE + ']"
                                                      QUERYOUT "' + @FULL_PATH + '\' + @FILE_NAME + '" -w -T -S ' + @@servername 

PRINT @OUTPUT_FILE_WRITE_COMMAND

EXECUTE @RESULT = master.sys.xp_cmdshell @OUTPUT_FILE_WRITE_COMMAND, NO_OUTPUT

PRINT @RESULT

EXECUTE ( 'DROP TABLE [' + @OUTPUT_TABLE + ']' )

So, the frustrating part is that I'm receiving an error, yet my file is not being written.

The output of PRINT @OUTPUT_FILE_WRITE_COMMAND is:

BCP ”SELECT CONTENT FROM [##temp878274]"
QUERYOUT "\\TXPDC-FS01\Profiles\cofarmer\My Sandbox\THCIC\Q2_2014\Burleson\PIPSUB2938718184092014251607.txt" -w -T -S TXPDC-STKSQL01

While the output of PRINT @RESULT is: 1

Yet nothing is being written. What am I doing wrong?


回答1:


Looks like the issue is the line break in the@OUTPUT_FILE_WRITE_COMMAND (and the erroneous double quote). Removing the line break worked for me:

DECLARE @OUTPUT_FILE_WRITE_COMMAND VARCHAR(1000) = 'BCP "SELECT CONTENT FROM [' + @OUTPUT_TABLE + ']" QUERYOUT "' + @FULL_PATH + '\' + @FILE_NAME + '" -w -T -S ' + @@servername 

Result: 0 and the file was created.



来源:https://stackoverflow.com/questions/26059604/sql-server-bcp-command-not-writing-nvarcharmax-variable-contents-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!