CUSTOM DELIMITER : SQL Server - CSV Export using stored procedure - sql-server

Begin
Declare #registration_no int = 101
declare #bcp varchar(8000)
set #bcp = 'sqlcmd -s, -W -Q "set nocount on; SELECT * FROM [Student_Management].[dbo].[Student] WHERE registration_no= '+ cast(#registration_no as nvarchar(10))+' " | findstr /v /c:"-" /b > "d:\student.csv"'
EXEC master..xp_cmdshell #bcp
end
The above statements export the table data as CSV correctly, but instead of comma-separated values, I want pipe(|) separated output. Where can I mention a custom delimiter(|)
Edit:
Begin
Declare #registration_no int = 101
declare #bcp varchar(8000)
set #bcp ='sqlcmd -s"|"-W -Q "set nocount on; SELECT * FROM [Student_Management].[dbo].[Student] WHERE registration_no= '+ cast(#registration_no as nvarchar(10))+' " | findstr /v /c:"-" /b > "d:\student.csv"'
EXEC master..xp_cmdshell #bcp
END

Begin
Declare #registration_no int = 101
declare #cmd varchar(8000)
set #cmd='sqlcmd -W -s"|", -Q "set nocount on; SELECT * FROM [Student_Management].[dbo].[Student] WHERE registration_no= '+ cast(#registration_no as nvarchar(10))+' " | findstr /v /c:"-" /b > "d:\student.csv"'
EXEC master..xp_cmdshell #bcp
END

Related

Output in double quotes for select * [duplicate]

This question already has answers here:
SQLCMD : Can we put double quotation mark to output file ?
(3 answers)
How to get export output in "real" CSV format in SQL Server Management Studio?
(17 answers)
Closed 1 year ago.
The following lines are working fine and exporting as CSV. I want all the comma-separated values in double-quotes. I want to export the results of SELECT * FROM [AbcSQL].[dbo].[Customer] WHERE... into CSV with all output values in "123" this format
BEGIN
Declare #custid as int
Declare #qry as varchar(8000)
Declare #cmd varchar(8000)
set #trcustomerid = 1234
set #qry = 'set nocount on; SELECT * FROM [AbcSQL].[dbo].[Customer] WHERE trcustomerid= ' + cast(#custid as nvarchar(10)) + ''
SET #cmd = 'sqlcmd -s, -S serverdetails, -W -Q "' + #qry + '" | findstr /v /c:"-" /b > "c:\Data\trCustomer.csv"'
EXEC master..xp_cmdshell #cmd
END

Exporting as CSV , Custom Select Statement

The following lines work fine in SQL server and export CSV as desired except for the commented line(--)
If I try to export using select * things work fine, but there are some custom outputs I need, hence using the commented select statement. It gives syntax error and the reason is also clear in the part where I have used REPLACE there are unclosed quotes. I am setting a varchar variable #qry hence already the query is in single quotes. The occurrence of quotes in between is terminating the query. How do I assign #qry this complete query without termination in middle?
BEGIN
Declare #custid as int
Declare #qry as varchar(8000)
Declare #cmd varchar(8000)
set #trcustomerid = 1234
set #qry = 'set nocount on; SELECT * FROM [AbcSQL].[dbo].[Customer] WHERE trcustomerid= '+ cast(#custid as nvarchar(10))+''
--set #qry = 'set nocount on; SELECT [LocationID],[LocationCode],[Description], convert(varchar, [CreateDate], 121) AS [CreateDate], REPLACE([Eligible], '"', '""')AS [Eligible] FROM [AbcSQL].[dbo].[Customer] WHERE trcustomerid= '+ cast(#custid as nvarchar(10))+''
SET #cmd ='sqlcmd -s, -S serverdetails, -W -Q "'+#qry+'" | findstr /v /c:"-" /b > "c:\Data\trCustomer.csv"'
EXEC master..xp_cmdshell #cmd
END

Passing/Using Scalar variable in extended stored procedure-exec master..xp_cmdshell

I have to export data from the Student table as CSV without using the export wizard. The below script works fine if we hardcode the registration number, but when using the variable #registration_no it gives an error : must declare scalar variable. On printing the #cmd the registration_no is correctly replaced by 101. Seems #registration is out of the scope of the exec master..xp_cmdshell
Begin
Declare #registration_no as int
set #registration_no = 101
Declare #cmd as nvarchar(4000)
set #cmd = 'sqlcmd -s, -W -Q "set nocount on; select * from [Student_Management].[dbo].[Student] where registration_no = #registration_no " | findstr /v /c:"-" /b > "d:\student.csv" '
exec master..xp_cmdshell #cmd
END
create procedure sp_CSV_Export
#regno int
as
Begin
Declare #registration_no int = #regno
declare #bcp varchar(8000)
set #bcp = 'sqlcmd -s, -W -Q "set nocount on; SELECT * FROM [Student_Management].[dbo].[Student] WHERE registration_no= '+ cast(#registration_no as nvarchar(10))+' " | findstr /v /c:"-" /b > "d:\student.csv"'
EXEC master..xp_cmdshell #bcp
end
This worked!

Stored procedure called from trigger does not run

I am trying to run a stored procedure from a trigger to ensure orders are printed in the order they were inserted into the database. If I run the stored procedure manually it completes in less than 20 seconds. If I run it from the trigger it never completes.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ARITHABORT OFF
GO
CREATE PROCEDURE [dbo].[usr_despatch_m2] #order VARCHAR(10)
AS
SET XACT_ABORT ON
SET NOCOUNT ON
--DROP TABLE #bundle (bundle int)
DECLARE #sql VARCHAR(1000), #result INT, #text varchar(1000)
SET #sql = 'D:\csserver\bin\runvtorddesp_m.bat '+#order
-- set #sql = 'command.com /c sdespatch '+ #order
EXEC #result = master..xp_cmdshell #sql, no_output
IF #result in (0,1010)
BEGIN
EXEC manufg.dbo.op_populate_shipping_data_dev #order
IF #order LIKE '[T,Y,R,S]%'
BEGIN
EXEC [SERVER2].sp_manufg.[dbo].[pod_print_can_inv] #order
END
SET #sql = 'command.com /c PRINT /D:\\SERVER1\MEM-SHIPPING-INVOICE \\SERVER1\e$\PODPDF\'+rtrim(#order)+'.PDF'
EXEC #result = master..xp_cmdshell #sql, NO_OUTPUT
END
BEGIN
SET #text = (SELECT
CASE #result
WHEN 0 THEN 'Order despatched successfully'
WHEN 1010 THEN 'Order despatched successfully'
WHEN 1 THEN 'Order error not found in order header'
WHEN 2 THEN 'Order at incorrect status'
WHEN 3 THEN 'Order despatch held'
WHEN 4 THEN 'Order is not web order'
WHEN 5 THEN 'Order not fully processed by DataLinx'
WHEN 6 THEN 'Order is in error'
WHEN 7 THEN 'Order is in error'
WHEN 8 THEN 'Order header is locked'
WHEN 9 THEN 'Stock item is locked'
WHEN 13 THEN 'Order number not found'
WHEN 33 THEN 'Unable to lock stock allocations (stallocm)'
WHEN 34 THEN 'Unable to lock stock batch file (stquem)'
WHEN 40 THEN 'Unable to update EIPOLASTDT system key'
WHEN 50 THEN 'Unable to unlock EDI order'
ELSE 'Order in error'
END )
SET #text = rtrim(#order) +' ' + #text
SET #sql = 'echo ' + #text + ' > E:\DespatchErrors\Manufg\'+rtrim(#order)+'.txt'
EXEC #result = master..xp_cmdshell #sql, no_output
SET #sql = 'command.com /c PRINT /D:\\SERVER1\MEM-SHIPPING-INVOICE \\SERVER1\e$\DespatchErrors\MANUFG\'+rtrim(#order)+'.txt'
EXEC #result = master..xp_cmdshell #sql, NO_OUTPUT
END
The trigger is simply
ALTER TRIGGER [dbo].[usr_order_despatch_m_c] on [dbo].[pod_mfg_inv]
instead of insert
as
SET XACT_ABORT ON
SET NOCOUNT ON
DECLARE #order varchar(10)
SET #order = (select order_no from inserted)
EXEC usr_despatch_m2 'T568138'
The stored procedure that appears to be bogging things down is
GO
SET QUOTED_IDENTIFIER ON
SET XACT_ABORT ON
SET ARITHABORT ON
GO
ALTER PROCEDURE [dbo].[pod_print_can_inv]
#myOrder CHAR(10)
AS
DECLARE
#mySql VARCHAR(1000),
#result INT
BEGIN
--Select the right report since Trade invoices are different to Retail dispatch notes
IF #myOrder LIKE 'R%'
BEGIN
SET #mySql = 'dtsrun /S SERVER2 /E /N PODCanRetailInvPDF /A "myFilter":"8"="(lfdinv = ""' + RTRIM(#myOrder) + '"")"'
END
-- Canadian Battle For Vedros Invoices
IF #myOrder LIKE 'Y%'
BEGIN
SET #mySql = 'dtsrun /S SERVER2 /E /N PODVedrosInvoiceWithTerms /A "myFilter":"8"="(lfdinv = ""' + RTRIM(#myOrder) + '"")"'
END
-- Canadian Trade Invoices
ELSE
BEGIN
SET #mySql = 'dtsrun /S SERVER2 /E /N PODCanTradeInvWithTerms /A "myFilter":"8"="(lfdinv = ""' + RTRIM(#myOrder) + '"")"'
END
EXEC #result = master..xp_cmdshell #mySql, NO_OUTPUT
IF #result = 0 BEGIN
WAITFOR DELAY '00:00:01'
SET #mySql = 'DEL \\SERVER1\E$\PODPDF\TST\' + RTRIM(#myOrder) + '.pdf'
EXEC #result = master..xp_cmdshell #mySql, NO_OUTPUT
WAITFOR DELAY '00:00:01'
SET #mySql = 'REN \\SERVER1\E$\PODPDF\TST\PDFCreatorDocument.pdf ' + RTRIM(#myOrder) + '.pdf'
EXEC #result = master..xp_cmdshell #mySql, NO_OUTPUT
WAITFOR DELAY '00:00:01'
-- Stop MSAccess on the server
SET #mySql = 'PSKILL msaccess.exe'
EXEC master..xp_cmdshell #mySql, NO_OUTPUT
WAITFOR DELAY '00:00:10'
/*
IF #myOrder LIKE 'Y%'
BEGIN
SET #mySql = 'COMMAND AcroRd32.exe /t "\\SERVER1\E$\PODPDF\TST\' + RTRIM(#myOrder) + '.pdf" "\\SERVER1\BACKOFFICE" "Canon iR-ADV C5235/5240 PCL5c" "IP_172.16.235.100"'
EXEC master..xp_cmdshell #mySql, NO_OUTPUT
END*/
SET #mySQL = 'MOVE \\SERVER1\E$\PODPDF\TST\'+RTRIM(#myOrder)+'.pdf \\SERVER1\E$\PODPDF'
EXEC #result = master..xp_cmdshell #mySQL, NO_OUTPUT
WAITFOR DELAY '00:00:05'
END
END
The DTS package is opening an access database on the remote server and generating a form. This works lightening quick if I just run the stored procedure but if I use the trigger it never completes.
HELP!!!
David Brown answered this for me.
You can't do this in a trigger because the data isn't committed yet. In any supported version of SQL Server you would need to write those commands into another table with an IDENTITY key, and have a background task read that table in order and execute the commands. Whether that also works in SQL 2000 I can't say :)

SQL Server output to a file using variable name

I want to send SQL Server output to a file which is working as expected. But if I pass the file path in a variable, It is not creating the file.
Working
:out 'C:\Temp.txt'
Not Working
DECLARE #BCVFileName VARCHAR(500)
SET #BCVFileName= 'C:\Temp.txt'
:out #BCVFileName
Could anyone please help me on this??
Thanks,
Mahesh
For this you need to store your query in Query file and then you can execute from command to store result to a text file as shown below.
>sqlcmd -E -S(Local)\SQLExpress -YourDBName -iC:\myQuery -oC:\Output.txt
Another way to use T-SQL and create a batch statement to execute via XP_CMDSHELL. Following script will help you to do the same just replace your query, ServerName with used variables.
SET NOCOUNT ON;
GO
DECLARE #sqlcmd varchar(1000);
PRINT 'using SqlCMD.exe';
SET #sqlcmd = 'sqlcmd -S' + ##SERVERNAME + ' -E -oc:\outfile.txt '
DECLARE #cmd varchar(1000);
SET #cmd = '-Q"SELECT RIGHT(REPLICATE('' '' , 6) + CONVERT(varchar, AddressID), 6 ) AS AddressID, CONVERT(varchar(10), ModifiedDate, 121) AS ModifiedDate FROM AdventureWorks.Person.Address ORDER BY ModifiedDate;"';
SET #sqlcmd = #sqlcmd + #cmd;
--SELECT #sqlcmd;
EXEC xp_cmdshell #sqlcmd, no_output;
PRINT 'using BCP.exe';
SET #cmd = '"SELECT RIGHT(REPLICATE('' '' , 6) + CONVERT(varchar, AddressID), 6 ) AS AddressID, CONVERT(varchar(10), ModifiedDate, 121) AS ModifiedDate FROM AdventureWorks.Person.Address ORDER BY ModifiedDate;"';
SET #sqlcmd = 'bcp ' + #cmd + ' queryout "c:\outfile2.txt" -c -T -S' + ##SERVERNAME
--SELECT #sqlcmd;
EXEC xp_cmdshell #sqlcmd, no_output;
regards

Resources