Search code examples
sql-servert-sqlbcp

Problems with bcp output


I have some problems with the following code. Main reason for this code is to export the SQL statement into a file. But it doesn't work and I don't see my mistake.

DECLARE @DBName VARCHAR(5000);
DECLARE @period VARCHAR(5000);
DECLARE @SQLEXE VARCHAR(5000);
DECLARE @SearchSchema VARCHAR(5000);

SET @period = '''2017-01-01 00:00:00'' AND ''2017-12-31 23:59:59'''


SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + @DBName+']');

SET @SearchSchema  =  REPLACE((SELECT name FROM sys.tables where name LIKE '%$Change Log Setup'), 'Change Log Setup', 'Change Log Entry');
SET @SQLEXE = 'bcp "SELECT [Entry No_]
      ,[Date and Time]
      ,[User ID]
      ,[Table No_]
      ,[Field No_]
      ,[Type of Change]
      ,[Old Value]
      ,[New Value]
      ,[Primary Key]
      ,[Primary Key Field 1 No_]
      ,[Primary Key Field 1 Value]
      ,[Primary Key Field 2 Value]
      ,[Primary Key Field 3 No_]
      ,[Primary Key Field 3 Value]
      ,[Record ID]
  FROM [dbo].[' + @SearchSchema + ']
  WHERE [Date and Time] BETWEEN '+@period+'" out "C:\Users\Public\Documents\1a_EY_change_log_entry.txt" -o "C:\Users\Public\Documents\1b_EYlog_change_log_entry.log" -c -T';
Exec master..xp_cmdshell @SQLEXE;

The error message is: enter image description here

Do you see my mistake?


Solution

  • This could be weird but it will work..

    Put the entire sql in single line instead of new lines

    SET @SQLEXE = 'bcp "SELECT [Entry No_],[Date and Time],[User ID],[Table No_],[Field No_],[Type of Change],[Old Value],[New Value],[Primary Key],[Primary Key Field 1 No_],[Primary Key Field 1 Value],[Primary Key Field 2 Value],[Primary Key Field 3 No_],[Primary Key Field 3 Value],[Record ID] FROM [dbo].[' + @SearchSchema + '] WHERE [Date and Time] BETWEEN '+@period+'" out "C:\Users\Public\Documents\1a_EY_change_log_entry.txt" -o "C:\Users\Public\Documents\1b_EYlog_change_log_entry.log" -d '+quotename(@dname)+' -c -T';
    

    Also this will not work as you are expecting

    EXECUTE ('USE [' + @DBName+']');
    

    Use the database parameter(-d) option present in bcp

    -d databasename