Stored Procedure results into a file only if not null - sql-server

I am trying to execute Stored Procedure on a regular basis using a SQL Job and store the results of this into a .txt file in a folder location.
I have used the BCP command which is like:
DECLARE #command VARCHAR(1000)
SET #command = 'BCP "Exec [DatabaseName].[dbo].[StoredProcedureName] " queryout "D:\In\ErrorDetails'+ '.txt" -c -T -t -k'
EXEC xp_cmdshell #command
I need this to execute only if results of SP are not null.

You can use temp table to store data generated by SP, if there are any rows - write it to file
USE tempdb
IF OBJECT_ID(N'#MyTempTable') IS NOT NULL
BEGIN
DROP TABLE #MyTempTable
END
SELECT * INTO #MyTempTable
FROM OPENROWSET('SQLNCLI', 'Server=HOME\SQLEXPRESS;Trusted_Connection=yes;',
'EXEC Test.dbo.StoredProcedureName');
IF (SELECT COUNT(*) FROM #MyTempTable) > 0
BEGIN
DECLARE #command VARCHAR(1000)
SET #command = 'BCP "USE tempdb SELECT * FROM #MyTempTable " queryout "D:\In\ErrorDetails'+ '.txt" -c -T -t -k'
EXEC xp_cmdshell #command
END

Related

BCP - Export CSV with header

I have run the following query to export my Ms SQL table as CSV. It working good. Now I want to add the field name as the first row. How is it possible?
declare #sql varchar(8000)
select #sql = 'bcp "select * from test_table" queryout C:\Test_SP\Tom.csv -c -t, -T -S' + ##servername
exec master..xp_cmdshell #sql
I know that I can specify the names #Red Devil answered. But the table is dynamic, Its fields are not fixed, It will change. I am trying to find a method to fetch the field names from the table definition and prepend it into the result CSV
Try this:
declare #sql varchar(8000)
select #sql = 'bcp "select 'col1', 'col2',... union all select * from test_table" queryout C:\Test_SP\Tom.csv -c -t, -T -S' + ##servername
exec master..xp_cmdshell #sql

Dynamic file creation with BCP Utility

I'm using BCP Utility to copy records out of table before deleting the records.
The function is working just fine, however, I need to copy the records to a new file for the every time I delete, instead of override the same file (as it is now).
It could be creating a new file with timestamp as prefix or something similar.
Any ideas?
My code
Declare #cmd varchar(1000) = 'bcp "select * from ##DeletedRecords" queryout
"C:\Delete\DeletedRecord.txt" -t, -c -T'
print #cmd
EXEC master..XP_CMDSHELL #cmd
just change the filename in the BCP command accordingly by appending date & time to the filename
example :
Declare #cmd varchar(1000);
select #cmd = 'bcp "select * from ##DeletedRecords" queryout '
+ '"C:\Delete\DeletedRecord'
+ convert(varchar(10), getdate(), 112) -- YYYYMMDD
+ replace(convert(varchar(10), getdate(), 108), ':', '') -- HHMMSS
+ '.txt" -t, -c -T'
print #cmd
EXEC master..XP_CMDSHELL #cmd

SQL Server 2008 R2: Export data using bcp command and store bcp output into variable

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.

SQL Server User Defined Table Types and BCP Export

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?

Why do I get an error in bcp query out where clause?

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.

Resources