I have an issue with bcp to create xml file.
If I execute the single query
SELECT #header, #inland
FOR XML RAW(''), ROOT('root'), ELEMENTS, TYPE
I receive the correct XML data.
But if i insert the query into exec master..xp_cmdshell
declare #cmd varchar(2000) = 'bcp "SELECT #header,#inland FOR XML RAW(''''),ROOT(''root''), ELEMENTS, TYPE" queryout "\\server01\TEMP_SW\XML_TMS\test_'+#num+'.xml" -U xx -P xxxxx -c -C ANSI -t;' ;
exec master..xp_cmdshell #cmd;
The system returns the error
SQLState = 37000, NativeError = 137
Error = [Microsoft][SQL Native Client][SQL Server]Must declare the scalar variable "#header".
SQLState = 37000, NativeError = 8180
Error = [Microsoft][SQL Native Client][SQL Server]Statement(s) could not be prepared.
#header is declared as XML
Where is the error?
Thanks and regards
The error is just what is being reported. When using QUERYOUT option of BCP you get a new, separate SQL connection within which your SQL statement is executed (really it's the xp_cmdshell that first opens a new OS thread... then bcp-queryout opens a new SQL connection). This statement knows nothing of any earlier "declare" or "set/select" statements you may have executed before your xp_cmdshell command. So, looking at your SQL statement as the stand-alone query that it is, of course you will get an error that your variables have not been defined.
To do what you are trying to do, can you just resolve the values of your variables as you are buidling the #cmd string? Like this:
declare #cmd varchar(2000)
select #cmd = 'bcp "SELECT ' + #header + ',' + #inland + ' FOR XML RAW(''''),ROOT(''root''), ELEMENTS, TYPE" queryout "\\server01\TEMP_SW\XML_TMS\test_'+#num+'.xml" -U xx -P xxxxx -c -C ANSI -t;' ;
exec master..xp_cmdshell #cmd;
It looks like you are aleady doing this with the #num variable you add into the string later on. Just do the same with your #header and #inland variables.
Related
I have a DB "Test" and table "demo"(TRANSACT TYPE,TRANSACT_NUMBER,BALANCE,CREDIT AMOUNT,ACCOUNTING_DATE).
my purpose is:
to create a procedure which exports all the data of the table "demo" to csv file (without using bcp utility)
So far i have written the following code for stored proc:
CREATE PROCEDURE Test1
AS
SELECT * FROM demo
GO
EXEC Test1
and the following script in which I used the bcp utility (which gets an error: SQLState = S1000, NativeError = 0 Error = [Microsoft][ODBC Driver 13 for SQL Server]Unable to open BCP host data-file):
DECLARE #ExportFolderName NVARCHAR(90);
DECLARE #ExportFileName NVARCHAR(90);
SET #ExportFolderName = 'C:\Export\';
SET #ExportFileName = #ExportFolderName + 'demofile' + '.csv';
DECLARE #SqlStatement varchar(8000)
DECLARE #BcpStatement varchar(8000)
SET #SqlStatement = 'exec [SInterface].[dbo].[Test1]'
SET #BcpStatement = 'bcp "' +#SqlStatement + '" queryout "' + #ExportFileName + '" -c -t","-r"\n" -T'
exec master..xp_cmdshell #BcpStatement
for this reason I try to find a solution in which bcp is not used
I want to export data using bcp command and the output of the bcp command should be stored in the variable.
My try:
DECLARE #Result varchar(max)
DECLARE #SQL nvarchar(max)
SET #SQL = N'Execute xp_cmdshell ''bcp "SELECT * FROM EMP" QueryOut "E:\BCP\Result.pec" -T -t#_# -c -o "E:\BCP\LogReport.txt"'''
EXEC sp_executesql #SQL, N'#Result nvarchar(75) OUTPUT', #Result =#Result output
PRINT(#Result)
But getting an error in the output:
output
------------------------------------------------------------------------------
bcp: Unable to open output file E:\BCP\LogReport.txt: No such file or directory
NULL
Questions:
1. How to store the above output result into the variable?
2. Given permission to the file and folder too, but still getting this error.
---------------------------------------- 1 -------------------------------------------
DECLARE #Result TABLE
(error_msg VARCHAR(800))
DECLARE
#SQL varchar(8000),
#Result_var VARCHAR(MAX)=''
SET #SQL = N'bcp "SELECT * FROM <MY_DATABASE>.<MY_SCHEMA>.<MY_TABLE>" QueryOut "E:\BCP\Result.pec" -T -t#_# -c -o "E:\BCP\LogReport.txt"'''
-- Insert the output from xp_cmdshell into the table #Result
INSERT INTO #Result (error_msg)
EXEC xp_cmdshell #SQL
-- Merge the rows
SELECT #Result_var = #Result_var + ' ' + ISNULL(error_msg,'') FROM #Result
-- Output in variable
PRINT #Result_var
--------------------------------------------------------------------------------------
2. For me, your command works, check access to folders and subfolders (for database user), check permissions on the sql server.
I can't seem to get this script to work. I'm getting the following error:
Msg 137, Level 16, State 1, Line 14
Must declare the scalar variable "#TVP_GLICU".
Can anyone tell me what am I missing?
Declare #TVP_GLICU TVP_GLICU
DECLARE #cmd varchar(500)
Declare #TimeStamp as nvarchar(100) = Replace((CONVERT(varchar(25), getdate(), 121)),':','')
--Insert Batch numbers in user defined table types
Insert Into #TVP_GLICU (ID)
Values ('563704')
Insert Into #TVP_GLICU (ID)
Values ('498721')
--select *
--From #TVP_GLICU
SET #cmd = 'BCP "EXECUTE [F0902].[D365O].[Get-F0911NewRecords]'+#TVP_GLICU+'" QUERYOUT "D:\D365O\DataSource\F0911\'+#TimeStamp+'.csv" -c -t\^, -T -S' + ##SERVERNAME + ''
EXECUTE MASTER..xp_cmdshell #cmd
You can't refer to a table variable from BCP that was created outside the scope of the query parameter. When BCP is executed, it creates a new session and the scope of table variables is limited to the session that created the table variable.
Problem is that you are concatenating string and are trying to append a table-valued type:
SET #cmd = 'BCP "EXECUTE [F0902].[D365O].[Get-F0911NewRecords]'+#TVP_GLICU+'" QUERYOUT "D:\D365O\DataSource\F0911\'+#TimeStamp+'.csv" -c -t\^, -T -S' + ##SERVERNAME + ''
Can you instead create a Staging table in the database and use its name in BCP query?
I'm new to SQL Server and write this query for save select result into csv file:
declare #Cycle_ID as int
set #Cycle_ID = 0
EXECUTE master.dbo.xp_cmdshell 'bcp "select [Telno],[Cycle],[Price] FROM [ClubEatc].[dbo].[CycleAnalysisTable] where cast([Price] as float)>'+ #Cycle_ID +' " queryout d:\download\behi.csv -t"|" -c -S VM_TAZMINDARAMA -U behzad -P beh1368421'
In where clause I write simple variable, but I get this error:
Incorrect syntax near '+'.
Please don't decrease my question! I'm new! Thanks
SQL Server doesn't recognize expressions in exec statements. So, try setting up the query first in a variable and using that:
declare #Cycle_ID as int;
set #Cycle_ID = 0;
declare #sql nvarchar(max);
set #sql = '
bcp "select [Telno],[Cycle],[Price] FROM [ClubEatc].[dbo].[CycleAnalysisTable] where cast([Price] as float)>'+ cast(#Cycle_ID as varchar(255)) +' ";
EXECUTE master.dbo.xp_cmdshell #sql queryout d:\download\behi.csv -t"|" -c -S VM_TAZMINDARAMA -U behzad -P beh1368421';
It seems curious to me that you are comparing a column called Price to a variable called #Cycle_ID, but that has nothing to do with the syntax issue.
EXEC xp_cmdshell 'bcp "select * from employee" queryout "C:\bcptest2.txt" -T
-SDemo -Usa -PPassword1 -c -t'
when i ran the above command to create a file and store the records from employee table in the file but i got the error as
SQLState = S1000, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]
Unable to open BCP host data-file NULL
-- Test 2
DECLARE #querytextNoVid VARCHAR(100)
DECLARE #querytext VARCHAR(100)
DECLARE #filelocation VARCHAR(100)
DECLARE #cmd VARCHAR(255)
IF OBJECT_ID('tempdb..#data2') is not null
begin
drop table #data2
END
CREATE TABLE #data2(name varchar(100),addres varchar(100))
insert into #data2 select 'Manas','pratap'
insert into #data2 select 'Ranga','Sasi'
select * from #data2
EXEC xp_cmdshell 'bcp "select * from #data2" queryout "C:\test\bcptest2.csv" -T -Sdemo -Usa -PPassword1 -c -t'
When i run the above script i got the error like
NULL
Starting copy...
SQLState = S0002, NativeError = 208
Error = [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name '#data2'.
SQLState = S1000, NativeError = 0
Error = [Microsoft][SQL Server Native Client 11.0]Unable to resolve column level collations
NULL
BCP copy out failed
NULL
--Any help on the above error
Please refer to article Unable to open BCP host data-file SQL Server error
You are required to grant write permissions to SQL Server service user NT Service\MSSQLSERVER on the file folder
I think you are not using Database name in your query, that's why the error.
you have your SELECT statement like this:
select * from DatabaseName.SchemaName.employee
Or, you have to provide an argument to specify the database name like:
EXEC xp_cmdshell 'bcp "select * from employee" queryout "C:\bcptest2.txt" -d "DatabaseName" -T -SDemo -Usa -PPassword1 -c -t'