I am using the following query to export data into a file:
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=C:\shared_files;HDR=YES;FMT=Delimited','SELECT * FROM [existing_file.csv]')
SELECT field_A, field_B, field_C FROM myTable
After executing, the result in the file (C:\shared_files\existing_file.csv) is:
myField_A,myField_B,myField_C
"1","customer 01","address 01"
"2","customer 02","address 02"
"3","customer 03","address 03"
I want to obtain it delimited by semicolon and without quotation marks, as the following example:
myField_A,myField_B,myField_C
1;customer 01;address 01
2;customer 02;address 02
3;customer 03;address 03
I've researched, but did not find the syntax for OPENROWSET options.
https://learn.microsoft.com/pt-br/sql/t-sql/functions/openrowset-transact-sql?view=sql-server-ver15
How to use OpenRowSet to insert data into a blank file?
INSERT INTO OPENROWSET Syntax with Dynamic T-SQL
If necessary, the file extension may be changed.
Does anyone knows how to set the options in the OPENROWSET above to get that desired result ?
The solution I've built, there's no need to use OPERNROWSET, as @Aaron Bertrand clearified it for me.
-- in the first line of the file to be created
INSERT INTO some_table_to_get_data
SELECT 'colName_A;colName_B;colName_C' --insert a customized header, using any desired delimiter
-- then insert data, using desired formatting and converting to varchar to concatenate it
INSERT INTO some_table_to_get_data
SELECT
CONVERT(varchar(1000),field_A)
+ ';' + LTRIM(RTRIM(CONVERT(varchar(1000),field_B)))
+ ';' + LTRIM(RTRIM(CONVERT(varchar(1000),field_C)))
+ ';' + LTRIM(RTRIM(CONVERT(VARCHAR, field_D, 103)))
FROM myTable
DECLARE @myFileName VARCHAR(100)
DECLARE @cmd VARCHAR(8000)
SET @myFileName = 'desiredNameForMyFile.txt'
SELECT @cmd = 'sqlcmd -h-1 -W -S myServerName -d myDatabaseName -U myLoginName -P myPasswordName -Q "SET NOCOUNT ON; select dados from dbo.some_table_to_get_data" -o "C:\mySharedPath\' + @myFileName + '" '
--PRINT(@cmd)
EXEC MASTER..xp_cmdshell @cmd