[dba-SQLServer] BCP out fails

jwcolby jwcolby at colbyconsulting.com
Fri Nov 30 11:25:34 CST 2012


I am trying to BCP out to text files using a stored procedure with passed parameters.  I have done 
this forever however I always just used a view.  In order to do that I have to have a view for each 
file.  Yuk.

So I am trying to use a SQL statement in variable @SQL.  I have assembled a SQL variable which looks 
like:

ALTER PROCEDURE [dbo].[usp_BCP_OneFileSQL]
	@DBName varchar(50), @OrderName varchar(50), @Selection varchar(50)
	-- Add the parameters for the stored procedure here
AS
BEGIN

DECLARE @SingleQuote VARCHAR(10)
SELECT @SingleQuote = ''''

Declare @SQLQuery varchar(8000)
	
SELECT @SQLQuery = 'SELECT PK, EM_Email, FName, EM_IP, EM_Source, Selection
			FROM dbo.vOrderBase
			WHERE (Selection = ' + @SingleQuote + @Selection + @SingleQuote + ')'
	
declare @sql varchar(8000)
	
select @sql = 'bcp "'+ @SQLQuery + '" queryout D:\PSM\Orders\PSM\' + @DBName + '\' + @OrderName + 
'-' + @Selection + '.txt -c -t, -T -SAzul'
	
print @SQL
--declare @sql varchar(8000)select @sql = 'bcp [' + @DBName + '].[dbo].[' + @TblName + '] out 
D:\PSM\Orders\PSM\PSM11275\' + @TblName + '.txt -c -t, -T -SAzul'

exec master..xp_cmdshell @sql

End

The old (commented out) declare for the sql statement does not work any more of course because of 
parameter changes.

The current @SQL evaluates to:

bcp "SELECT PK, EM_Email, FName, EM_IP, EM_Source, Selection
	FROM dbo.vOrderBase
	WHERE     (Selection = 'PSP-01')" queryout D:\PSM\Orders\PSM\PSM11280\PSM11280-PSP-01.txt -c -t, -T 
-SAzul

Which looks good.

Any clue what is wrong with what I am doing?  I have been doing the "dedicated query" forever and 
can continue to limp along doing that but using a dynamically constructed SELECT query would make 
things so much simpler.

-- 
John W. Colby
Colby Consulting

Reality is what refuses to go away
when you do not believe in it



More information about the dba-SQLServer mailing list