Save Sql Recordset into the Flat text file? - sql

i need to dump my sql query result into the text file. i have created the following query,
DECLARE #cmd VARCHAR(2048)
SET #cmd = 'OSQL -localhost -CRN370 '
+ ' -UCRN370 -PCRN370'
+ ' -Q"SELECT TOP 5 GageId FROM EwQMS370..msgages"'
+ ' -oc:\authors.txt'
EXEC master..xp_cmdshell #cmd, NO_OUTPUT
The above query created the text file authors.txt. But the content of the file shows the following error message
" Error: Conflicting switches : -U and -E "
Any help really appreciated

Start -> Run... -> cmd
And try to execute this command without -o key and its value :)
I think problem is with command parameters.
And what is the parameter "-localhost". Beybe you forgot about S key? And what is the -C parameter key?
Try this:
DECLARE #cmd VARCHAR(2048)
SET #cmd = 'OSQL -Slocalhost '
+ ' -UCRN370 -PCRN370'
+ ' -Q"SELECT TOP 5 GageId FROM EwQMS370..msgages"'
+ ' -oc:\authors.txt'
EXEC master..xp_cmdshell #cmd, NO_OUTPUT

Related

String formatting issue for creating the SQL query for BCP

I want to use some of the static data to the new BCP query and export the extracted data to CSV. The static data are generated as a result after running some BCP command earlier.
But I have been facing string formatting issue for creating the SQL query using those variables and generate a SQL command.
I simply want to use the following query in the BCP command:
select #version, #TotalRecords
BCP query I have used is:
DECLARE
#version varchar(10),
#HeaderCmd VARCHAR(500),
#StateCode varchar(2),
#v_Header_path varchar(255),
#TotalRecords int;
SET #StateCode = 'AL'
SET #version = 'ver4'
SET #TotalRecords = 20
SET #v_Header_path ='c:\csv\test\' + #StateCode + '_header.txt'
SELECT #HeaderCmd = 'bcp '
+'"select '+ #version+ '" '
+ ' queryout ' + #v_Header_path
+ ' -c -t, -T' ;
SELECT #HeaderCmd AS 'Command to execute';
EXECUTE master..xp_cmdshell #HeaderCmd;
The above command is generating the following sql command:
bcp "select ver4" queryout c:\csv\test\AL_header.txt -c -t, -T
and giving the error as:
Error = [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'ver4'.
I wanted to export the value of #version and #TotalRecords into the CSV file.
But I am stuck in a string formatting issue for creating the SQL query as the string.
Give the column a name, and output the value in quotes. Use consecutive single quotes to pass a quote to the string:
select #HeaderCmd =
'bcp ' +
'"select ''' + #stateCode + ''' as stateCode, ''' + #version + ''' as version, ' + convert(varchar(10), #totalRecords) + ' as totalRecords" ' +
' queryout ' + #v_Header_path +
' -c -t, -T' ;
This should then output:
bcp "select 'AL' as stateCode, 'ver4' as version, 20 as totalRecords" queryout c:\csv\test\AL_header.txt -c -t, -T

Unable to Update file After SQL insert SQLRPGLE

Good Day all,
I am writing a program to build a report where I build the SQL statement to insert selected records into a file and after that insert I would like to do a simple update on the file to change a select fields in some records.
The problem is that after the insert is run, anytime I try to update the file I get a Record or File in use error.
I have tried updating it programatically with sqlrpgle and with I/O read and set functions and I have even tried just updating the file in STRSQL after I run the program and I all come to the same error.
I suspect I am not closing something properly but I am not sure what.
Code is as follows
// Assign SQL Query
sqlstmt = 'insert into jallib/orhsrpt ('+
'oacctd, oacmp, oaord, oacust, o8type, ' +
'o8text, o8date, o8time ) ' +
'select oacctd, oacmp, oaord, oacust, ' +
'o8type, o8text, o8date, o8time ' +
'from r50files.vcohead ' +
'join r50files.vcopkct ' +
'on oacmp = o8cmp and oaord = o8ord ' +
'where oacmp = 1 ' +
'and o8type not in (' +
'''C'',''a'',''H'',''E'',''F'', '+
'''A'',''1'',''N'',''M'') ' +
'and oacctd = ' + curdate +
' order by oaord, o8time ';
// Prepare for multiple sql statements
exec sql
Set Option Commit = *NONE;
// Clear output file before executing SQL
exec sql
Delete from jallib/orhsrpt;
if sqlcode < *zeros;
errmsg = 'Delete of file failed';
endif;
// Execute SQL Insert statement
exec sql prepare sqlsel from :sqlstmt;
exec sql execute sqlsel;
if sqlcode < *zeros;
errmsg = 'Insert of file failed';
endif;
// Update file data
exec sql
Set Option clossqlcsr = *ENDMOD;
exec sql
Update jallib/orhsrpt
set o8text = 'Order Invoiced'
where o8type = 'I'
The error from STRSQL is as follows
Row or object ORHSRPT in JALLIB type *FILE in use.
The quick answer is that the insert is not closed because your module hasn't ended according to the Set Option you specified. However, the correct answer here is that there is no reason for you to be using dynamic SQL statements at all. They are slower and more error prone in general and you run into issues like this one. You should instead use a regular embedded SQL statement as below:
exec sql
set option commit = *NONE;
// Clear output file before executing SQL
exec sql
delete from jallib/orhsrpt;
if sqlstate <> *zeros;
errmsg = 'Delete of file failed';
endif;
exec sql
insert into jallib/orhsrpt (
oacctd, oacmp, oaord, oacust,
o8type, o8text, o8date, o8time )
select oacctd, oacmp, oaord, oacust, o8type,
o8text, o8date, o8time
from r50files.vcohead join r50files.vcopkct
on oacmp = o8cmp and oaord = o8ord
where oacmp = 1 and o8type not in (
'C','a','H','E','F', 'A','1','N','M') and
oacctd = :curdate
order by oaord, o8time;
exec sql
update jallib/orhsrpt
set o8text = 'Order Invoiced'
where o8type = 'I'
This is better practice and should solve your issue.

Is it possible to export 'PRINT' commands into a file via bcp?

I want to export a result of a PRINT command. I don't want to use the normal SQL Server logs. Is that possible with bcp? Because the following command does not work.
Example:
SET #IPE = 'bcp PRINT ''Test'' queryout ' + #Path + '1b_Log_change_log_entry.txt -c -T'
Result:
Starting copy...
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC Driver 13 for SQL Server]BCP host-files must contain at least one column
SQLState = S1000, NativeError = 0
Error = [Microsoft][ODBC Driver 13 for SQL Server]Unable to resolve column level collations
NULL
BCP copy out failed
NULL
Print is not a query but Select is.. Try Select instead of Print
SET #IPE = 'bcp SELECT ''Test'' queryout ' + #Path + '1b_Log_change_log_entry.txt -c -T'

How to create text files using table content for name and text inside in SQL Server

I have following table:
1 One TEXT_ONE
2 Two TEXT_TWO
3 Three TEXT_Three ...
I want run SQL Query that will creates txt files in specific folder:
C:\Files\One.txt (Text inside - TEXT_ONE)
C:\Files\Two.txt (Text inside - TEXT_TWO)
C:\Files\Three.txt (Text inside - TEXT_Three)...
I'm not so good in SQL, so any help appreciates=)
Thanks
I found my own way. It's probably not absolute answer for my question, but the idea completed.
So, I've created bcp Command that needs to be executed from Command Line
'bcp "SELECT ColumnName FROM DBName.schema.TableName WHERE IDCol = ' + CAST(IDCol as varchar(2)) + '" QUERYOUT .\' + ColumnForFileName + '.txt -FullServerName -T -c'
You can run select statement in SQL. Here is my example:
SELECT sp.[SessionPageID]
,sp.[SummaryBody]
,sp.[MainTableBody]
,sf.[FileName]
,'bcp "SELECT SummaryBody FROM WLS_3E_TIMELOAD_APP.dbo.SessionPage WHERE SessionPageID = ' + CAST(sp.[SessionPageID] as varchar(2)) + '" QUERYOUT .\SB_' + sf.[FileName] + '_Session.txt -SCHAKHAU-T430\CHAKHAU -T -c'
,'bcp "SELECT MainTableBody FROM WLS_3E_TIMELOAD_APP.dbo.SessionPage" QUERYOUT .\MB_' + sf.[FileName] + '_Session.txt -MYLapTOP\LOCAL -T -c'
FROM [SessionPage] sp
JOIN SourceFile sf ON sf.SourceFileID = sp.SourceFileID
If you run this kind of query in result you will get all your bcp commands, so you then can execute them from Command Line

EXEC MASTER.DBO.XP_CMDSHELL MOVE

I am working on a FILE that I need to move from one loacation to another, but when I run the code below I keep getting an error that it has the incorrect syntax. When I print the #Move statement I get this: (Which is what I think I should get)
MOVE \appdev1\sqltest\RedFlag\RedFlag Address Change New Debit Issued.pdf \appdev1\sqltest\RedFlag\2013-10-24_REDFLAG_.pdf
I am trying to run it like this:
EXEC MASTER.DBO.XP_CMDSHELL #MOVE
Any suggestions on what I am doing wrong? Do I need to add the ' in front of the Move statement?
You have spaces in your paths/filenames, so you need to surround with double quotes.
SET #MOVE = 'MOVE "\\appdev1\... Issued.pdf" "\\appdev1\..._.pdf"';
If you are constructing a path from variables, this doesn't change anything. Staying in T-SQL, you would have parameters like this I presume:
SET #MOVE = 'MOVE "' + #OldFile + '" "' + #Printed + '"';
You'll have to work it out yourself if you are doing this in some other language. Here is a short demonstration of how it works in T-SQL:
DECLARE #MOVE VARCHAR(255),
#OldFile VARCHAR(255) = '\\foo\some filename.pdf',
#Printed VARCHAR(244) = '\\blat\something else.pdf';
SET #MOVE = 'MOVE "' + #OldFile + '" "' + #Printed + '"';
PRINT #MOVE;
Results:
MOVE "\\foo\some filename.pdf" "\\blat\something else.pdf"
I don't see any extra quotes, so maybe those are coming from whatever value you have in your parameters.