Click here to Skip to main content
15,889,863 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi
I have in error in Mssql Store procedure using BCP bulk transfer data into csv file
Error : - "Must declare the scalar variable "@EXPORT_EXCEL"

Pls advice me.

Thank you in advance

Maideen

What I have tried:

	DECLARE @Servername varchar(100)
	SET @Servername ='xxxxxxx'

   DECLARE @EXPORT_EXCEL TABLE
    (
		[BL_NO] [varchar](30) NULL,
		[VESSAL_NAME] [varchar](100) NULL,
		[CONTAINER_NO] [varchar](50) NULL,
		[CONTAINER_TYPE] [varchar](10) NULL

	)
    

		INSERT INTO @EXPORT_EXCEL (BL_NO, VESSAL_NAME,CONTAINER_NO,CONTAINER_TYPE) 
		SELECT BL_NO, VESSAL_NAME,CONTAINER_NO,CONTAINER_TYPE FROM [dbo].[ZR_tbl_Export_FILE] 
		ORDER BY VESSAL_NAME


declare @sql varchar(8000)
select @sql = 'bcp guard_security.dbo.' + @EXPORT_EXCEL + 'out c:\ExportExcel\Export_FILE.csv -c -t, -T -S' +  @servername
	   exec master..xp_cmdshell @sql
Posted
Updated 23-Jul-19 3:38am

1 solution

@EXPORT_EXCEL isn't a variable, it's a Table variable which means it is scoped to the procedure or command that is executing: as soon as the execution ends (which is will right after issuing the exec command) the table will be destroyed - you can't just stick the table into an SQL command where the system expects a table name as part of it's DB.Table specification!
And even if you could, you wouldn't pass the table content to the operating system using that code as it wouldn't exist when bcp started executing!

To output in CSV, why not just use XML PATH:
SQL
SELECT SUBSTRING(
(SELECT ',' + CONVERT(varchar, Id) FROM myTable WHERE date BETWEEN '2011-01-01' AND '2012-01-01'
FOR XML PATH('')),2,100000) AS CSV
And write that?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900