I use simple code
declare #sql varchar(8000)
select #sql = 'bcp ExcelAnalysis.dbo.ClearDB out c:\csv\comm.txt -c -t, -T -S '+ ##servername
exec master..xp_cmdshell #sql
but this code export all my table, but i need only some fields and conditions
like:
declare #sql varchar(8000)
select #sql = 'bcp
SELECT
,[vl]
,[data]
,[URL]
,[parse]
,[Strata]
,[Id]
FROM [ExcelAnalysis].[dbo].[ClearDB] where [data]> "01.05.2017" and NOT [vl] ="mag"and NOT [vl] ="Maxximo" out c:\csv\status.txt -c -t, -T -S '+ ##servername
exec master..xp_cmdshell #sql
but if i use any fields, the bcd returns message with his syntax.
How do correct?
First Part : Create a view in database and second part to execute statement to get results into CSV.Let me know if you need more help
use [ExcelAnalysis].
go
;
create view [dbo].[vw_ClearDB] as
SELECT
[vl]
,[data]
,[URL]
,[parse]
,[Strata]
,[Id]
FROM [dbo].[ClearDB] where [data]> "01.05.2017" and NOT [vl] ='magand'
NOT [vl] ='Maxximo'
GO
;
declare #sql varchar(8000)
select #sql = 'bcp ExcelAnalysis.dbo.vw_ClearDB out c:\csv\comm.txt -c -t, -T -S '+ ##servername
exec master..xp_cmdshell #sql
Bcp queryout option should be used.
Syntax would be:
SET #sql = 'bcp "SELECT [vl]
,[data]
,[URL]
,[parse]
,[Strata]
,[Id]
FROM [dbo].[ClearDB]
WHERE [data] > ''01.05.2017''
AND NOT [vl] =''mag''
AND NOT [vl] =''Maxximo''"
queryout c:\csv\comm.txt
-c -t, -T -S '+ ##servername + '\' + ##servicename
Related
I had the BCP command working until I added the where clause. The use of the single quote around a char value is causing a syntax error. I have tried embedding triple single quotes and also tried using double quotes with success. Any ideas?
Use tmseprd
DECLARE #sql VARCHAR(8000);
SELECT #sql = 'bcp "select studentid from tmseprd.dbo.Feith_Emas_Compare Where status = 'U' and counselor >199 and stage > 200 " queryout "C:\EMAS_Feith\advmove.txt" -c -t, -T -S' + ##Servername;
EXEC master..xp_cmdshell #sql;
You could use '' and space after -S:
Select #sql = 'bcp "select studentid from tmseprd.dbo.Feith_Emas_Compare Where status = ''U'' and counselor >199 and stage > 200 " queryout "C:\EMAS_Feith\advmove.txt" -c -t, -T -S ' + ##Servername;
I am trying to crate a CSV export file using BCP with a the datetime stamp in the file name. Everything appears correct but I keep getting errors around the + sign.
BEGIN
SET NOCOUNT ON
DECLARE #mydate DATETIME
DECLARE #filename VARCHAR(40)
SET #mydate = GETDATE()
SET #filename = 'C:\TEMP\TEST-'+CONVERT(varchar,FORMAT(#mydate,'yyyyMMdd-
hhmmss'))+'.csv'
exec master..xp_cmdshell 'bcp "select
CHAR(34)+""SampleNo""+CHAR(34),CHAR(34)+""Analysis
Code""+CHAR(34),CHAR(34)+""Analyte Name""+CHAR(34),CHAR(34)+""Old
Result""+CHAR(34),CHAR(34)+""New
Result""+CHAR(34),CHAR(34)+""ChangeDate""+CHAR(34)+CHAR(44) union all
SELECT CHAR(34)+SAMPNO+CHAR(34), CHAR(34)+ACODE+CHAR(34),
CHAR(34)+ANLNAME+CHAR(34), CHAR(34)+OLDRESULT+CHAR(34),
CHAR(34)+NEWRESULT+CHAR(34), CHAR(34)+CHANGEDATE+CHAR(34)+CHAR(44)
FROM TEST.dbo.MODIFY_EXPORT" QUERYOUT ' + #filename + ' -S SERV2012R2 -U sa -P password -c -t","'
END;
I have a procedure which is for exporting data from table to .DAT file. There's a job running on it which calls SP every 10 Min. .DAT file contains H= column names, B= table data, T= No of rows processed(.SIG file appends this to .DAT file).
Following is the stored procedure :
CREATE PROCEDURE [dbo].[Test_Export] #count2 VARCHAR(10)
AS
BEGIN
SET NOCOUNT ON;
--Alerts_Balance
DECLARE #bcp_sql VARCHAR(1000)
DECLARE #filename VARCHAR(200), #count1 VARCHAR(10)=20000
SET #filename = 'C:\Test'+'.DAT';
SELECT #bcp_sql = 'bcp "SELECT ''H'',''Name'',''City'',''State'',''Country'' union all SELECT top 10 ''B'', [Name],[City],[State],[Country] FROM Test_Table" queryout ' + #filename + ' -c -t, -T -S '+ ##servername
EXEC master.sys.xp_cmdshell #bcp_sql
SELECT #bcp_sql = 'bcp "SELECT ''T'', '+cast(IIF(cast(#count1 as int)>cast(#count2 as int), #count2+2, #count1+2) as varchar(10))+'" queryout '+ #filename + '.sig -c -t, -T -S '+ ##servername
EXEC master.sys.xp_cmdshell #bcp_sql
SELECT #bcp_sql = 'type ' + #filename + '.sig >> "' + #filename + '"'
EXEC master.sys.xp_cmdshell #bcp_sql
SELECT #bcp_sql = 'copy nul: ' + #filename + '.sig'
EXEC master.sys.xp_cmdshell #bcp_sql
EXEC (#bcp_sql);
END
It was working fine before with proper data format in .dat.
From couple of days, sometimes .dat file contain no "B" (body) data. Sometimes SIG file appends T 2 times to .DAT file on PROD environment. Sometimes it gives correct output also. This issue is coming only on PROD environment
Any idea why it is behaving like this?
I try to make a SQL statement to create a .txt file for each id that added to database, but this not working. I try this:
DECLARE #FileName varchar(50), #bcpCommand varchar(2000)
SET #FileName = REPLACE('G:\'+CONVERT(char(8),GETDATE(),1)+'.txt','/','-')
SET #bcpCommand = 'bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "'
SET #bcpCommand = #bcpCommand + #FileName + '" -U garth -P pw -c'
PRINT #bcpCommand
and of course I need this result savede in G:/, but this not working for me. My db name are testDB
Did you mean you want to create a bcp file for each database? Simply loop over all the databases, and ensure you specify the database name parameter for your bcp statement so it knows what database to execute the queryout query in. One other thing you will need to fix though, is the filename. You can modify it below to append the db name to the output file, so you do not end up overwriting each results.
DECLARE #FileName varchar(50), #bcpCommand varchar(2000)
declare #x int = 5
declare #y int
declare #dbname varchar(100)
select #y = max(database_id) from sys.databases
while #x <= #y
begin
select #dbname = name from sys.databases where database_id = #x
if #dbname is not null
begin
SET #FileName = REPLACE('G:\'+CONVERT(char(8),GETDATE(),1) +'.txt','/','-')
SET #bcpCommand = 'bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "'
SET #bcpCommand = #bcpCommand + #FileName + '" -U garth -P pw -c -d"' + #dbname + '"'
PRINT #bcpCommand
end
set #x = #x + 1
end
Sample results:
bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "G:\05-16-15.txt" -U garth -P pw -c -d"db1"
bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "G:\05-16-15.txt" -U garth -P pw -c -d"db2"
bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "G:\05-16-15.txt" -U garth -P pw -c -d"db3"
bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "G:\05-16-15.txt" -U garth -P pw -c -d"db4"
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