Can I specify an input sql file with bcp? - sql

How can I specify an input sql file with a long query when using bcp? I tried using the -i option but it keeps complaining about a command-line error with no extra information. Is this possible?

I had this problem today and found a convenient workaround, at least in an ad-hoc situation.
Temporary tables can be created by any user with connect permissions. This means you can also create GLOBAL temporary tables.
Just run your query in enterprise manager (or sql cmd or whatever) using SELECT ...INTO with a global temporary table e.g.
SELECT *
INTO ##mytemptable
FROM SomeTable
WHERE [massive where clause, for example]
You can then use the temporary table in the BCP query with a simple
SELECT * FROM ##mytemptable
Then drop the temp table through enterprise manager
DROP TABLE ##mytemptable

I did other way for fix that.
I create a batch file which read a file and send your content in bcp command. See:
#ECHO off
SETLOCAL EnableDelayedExpansion
SET queryFile=%1
SET outFileName=%2
FOR /F "delims=" %%i IN (%queryFile%) DO SET join=!join! %%i
ECHO %join%
bcp "%join%" queryout %outFileName% /S.\SQLE_CAESAR /d /c /t"|" /T
That script receive two parameters:
Filename which has a query;
Filename for export data;
Execute a script in cmd like that:
export-query.bat query.sql export.txt
I hope helped.

As far as I'm concerned the BCP utility only supports Transact-SQL queries directly written to the command line. Ex:
bcp "SELECT Name FROM AdventureWorks.Sales.Currency" queryout Currency.Name.dat -T -c
According to its reference the "-i" option:
Specifies the name of a response file, containing the responses to the command prompt questions for each data field when a bulk copy is being performed using interactive mode (-n, -c, -w, or -N not specified).
Notice that it differs from the sqlcmd Utility "-i" option:
Identifies the file that contains a batch of SQL statements or stored procedures. Multiple files may be specified that will be read and processed in order (...)

try :
query=$( cat < /file.sql )
export query
bcp "${query}" queryout /home/file.csv

Multi-line queries can be given to bcp easily using powershell:
PS> $query = #'
select *
from <table>
'#
PS> bcp $query queryout <outfile> -d <database> -T -S <server> -c

I had face same issue, may not be a very good approach. However, I did something like the following
bcp "declare #query nvarchar(max) set #query = (SELECT * FROM OPENROWSET(BULK 'F:\tasks\report_v2.sql', SINGLE_CLOB) AS Contents) exec sp_executesql #query" queryout %outFileName% /c /C RAW -S . -U sa -P 123 -d blog /T
And I must say, if you use like global temp table then global temp table is dropped itself of after query executed. you can't use this at some situations

What really worked for me is this:
#ECHO off
setlocal enableextensions enabledelayedexpansion
SET "queryFile=%1"
SET "outFileName=%2"
SET RESULT=
FOR /F "delims=" %%i IN ('type %queryFile%') DO SET RESULT=!RESULT! %%i
echo %RESULT%
rem bcp "%RESULT%" queryout %outFileName% -t^ -r \n -T -k -c -d DB_NAME -S SERVER_NAME
type file is the equivalent of cat file in unix

What I did with complex queries was create a stored procedure with the desired statement and call it from BCP:
bcp "exec db.schema.stored_procedure" queryout "c:\file.txt" -T -S localhost -t "|" -c
This worked great for me. Greetings!

I made my own script (called of bulk.sh) to do this (not optimal and not best practice... The script is too ugly, but very functional).
#!/bin/bash
input="SQL_FILE.sql"
count=0
const=1000
lines=()
mkdir -p bulk
while IFS= read -r line
do
lines+=("$line")
count=$((count+1))
check=$((count % const))
if [[ $check -eq 0 ]]; then
bulk="${lines[*]}"
unset lines
number=$(printf "%010d" $count)
echo $bulk > "bulk/bulk${number}.sql"
bulk=""
fi
done < "$input"
FILES="bulk/*"
for f in $FILES
do
echo "Processing $f file..."
sqlcmd -S SERVER -d DATABASE -U USER -P "PASSWORD" -i "$f"
sleep 2s
done
You can try it, with:
$ docker run -v /path/to/your/sql/file/folder:/backup -it mcr.microsoft.com/mssql-tools
$ bash bulk.sh

Related

Unexpected argument executing cmdexec on a SQL job to export to CSV

I try to run this on a SQL job:
sqlcmd -S . -d CI_Reports -E -s"," -W -Q "SET NOCOUNT ON SELECT * FROM [dbo].[Table]" > D:\Test.csv
How can I fix this error?
Sqlcmd: '> D:\Test.csv': Unexpected argument.
Have you tried like this -
sqlcmd -S . -d CI_Reports -E -s"," -W -Q "SET NOCOUNT ON SELECT * FROM [dbo].[Table]" -o D:\Test.csv
where -o output_file which would identify the file that receives output from sqlcmd.
Additionally you could try BCP which is best suited for bulk coping data between an instance of Microsoft SQL Server and a data file in a user-specified format.
Read more here.

How to import several sql files into postgreSQL using batch script?

I have a set of sql files
file1.sql
file2.sql
....
that contain table inserts INSERT INTO <tablename> (...) VALUES (....); in a directory. I would like to add a command into a existing batch file so that it iterates over each file.
Currently I use the command
<postgreSQLCommandWithParameters> -U <user> -d <database> -f <pathToSQL>\complete.sql -q
I looked into a for loop but I missing the parameter to point to the correct directory.
for %%G in (*.sql) do <postgreSQL> -U <user> -d <database> -E -i"%%G"
Therefore how can I use a for loop to iterate over all sql files which contain insert commands?
As a side question: And what is the syntax in the for loop in batch scripts?
So I used the following command
FOR /F "tokens=4 USEBACKQ" %%F IN (`dir <pathToSQLFiles> ^| findstr .sql `) DO (
<postgreSQL> %1 -U <user> -d <database> -f <pathToSQLFiles>\%%F -q
)
And here are some cliffnotes
"tokens=4 USEBACKQ" takes the numbered items to read from each line and also includes names with space in them
^| findstr .sql filters all SQL files

how export a table of database postgres to a csv with qt?

Already has the connection succesful.
With qtsqlquery. Seem imposible execute the copy sentence of the postgresql.
For example:
execute this query on qt:
COPY table TO 'D:/table.csv' DELIMITER ',' CSV HEADER;
After study a little bit, found a script on the folder of installation of PostgreSQL (.../scripts), then modified the script to executed the command COPY TO. Because the QSQLQUERY Definitely don't executed the command COPY. Here are the Script on win7.
for /f "delims=" %%a in ('chcp ^|find /c "932"') do # SET CLIENTENCODING_JP=%%a
if "%CLIENTENCODING_JP%"=="1" SET PGCLIENTENCODING=SJIS
if "%CLIENTENCODING_JP%"=="1" SET /P PGCLIENTENCODING="Client Encoding [%PGCLIENTENCODING%]: "
REM Run psql
"D:/PostgreSQL\bin\psql.exe" -h localhost -U USER -d DATABASE -p 5432 --no-password --command="\copy (select * from TABLE) TO './EXPORT_TABLE.csv' CSV HEADER"

How do I run a script using a BAT file?

I would like to have a BAT file open a sql server script. Currently I have this code in the sql file:
declare #path varchar(255), #mydb varchar(50)
SELECT #mydb = 'timeclockplus'
select #path = 'C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\Backup\'
+ #mydb + '-' + convert(varchar(8),getdate(),112) + '.bak'
BACKUP DATABASE #mydb TO DISK = #path
How do I open this SQL file from a BAT file?
I am currently trying to run it like this:
C:\Program Files\Microsoft SQL Server\80\Tools\Binn\osql -E
-S Sql server-hl7\timeclockplus timeclockplus.sql -oresults.txt
but OSQL does not exist in the BINN directory,
You should invoke the sqlcmd command-line tool from your batch file. Assuming your sql file is "backup.sql", the command line would be something like:
sqlcmd -E -S yoursqlinstance -i backup.sql
-E uses trusted connection, replace with -U and -P if you need to specify a SQL username and password. See also this article with examples.
sqlcmd -S 127.0.0.1 /E -i MySqlScript.sql
Replace /E with /U and /P if you don't have trusted connection
If you want a much better answer, here it is:
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
:: batch file for sql query
SET FIELDVAL=Empty
SET DBNAME=MYDB
SET SQLSTRING=SELECT column_name(s)^
FROM table_name1^
INNER JOIN table_name2^
ON table_name1.column_name=table_name2.column_name^
AND table_name2.field=%FIELDVAL%
ECHO !SQLSTRING!
ECHO.
sqlcmd.exe -b -S localhost -E -d !DBNAME! -Q "!SQLSTRING!" -W
ECHO Query is done. Hit any key to close this window....
pause>nul
Start > Run > Type Cmd.
MyDrive:\Mypath\Mybat.bat
=)

DOS command to execute all SQL script in a directory and subdirectories

I need a DOS command or a batch (.bat) file I can execute to run all the *.sql scripts in a directory and its subdirectories. What would the solution be?
The following will get you started
for /r %f in (*.sql) do echo %f
Run from the command line that will print the names of all the SQL files in the current directory and all sub directories.
Then substitute sqlcmd <connection args> -i%f for echo %f to execute the scripts.
Hope this helps.
Here you go. This batch file will execute all sql files in a directory and its subdirectories. It will also create an output.txt file with the results so you can see errors and whatnot. Some notes on batch file:
[YourDatabase] is the name of the database you want to execute the scripts against.
[YourPath] is the path of where you keep all the scripts.
[YourServerName\YourInstanceName] is the SQL server name and instance name, separated with a '\'
You'll want to replace the text after the '=' for each variable with whatever is appropriate for your server
Be sure NOT to put spaces around the '='
Do not put any quotes around [YourPath]
Make sure that [YourPath] has a '\' at the end
SET Database=[YourDatabase]
SET ScriptsPath=[YourPath]
SET ServerInstance=[YourServerName\YourInstanceName]
IF EXIST "%ScriptsPath%output.txt" del "%ScriptsPath%output.txt"
type NUL > "%ScriptsPath%output.txt"
FOR /R "%ScriptsPath%" %%G IN (*.sql) DO (
sqlcmd -d %Database% -S %ServerInstance% -i "%%G" -o "%%G.txt"
echo ..................................................................................... >> "%ScriptsPath%output.txt"
echo Executing: "%%G" >> "%ScriptsPath%output.txt"
echo ..................................................................................... >> "%ScriptsPath%output.txt"
copy "%ScriptsPath%output.txt"+"%%G.txt" "%ScriptsPath%output.txt"
del "%%G.txt"
)
for %f in ("c:\path\to\dir\*.sql") do sqlcmd -S [SERVER_NAME] -d [DATABASE_NAME] -i "%f" -b
Try a for loop. The options of this command have evolved and I'm not sure what version of DOS you are using, but assuming that DOS includes "cmd.exe from Windows XP", something like this could work:
for /r . %f in (*.sql) do #echo %f
Ok, this will only print the names of the files. I'm assuming you already have a program that you can run from the command line that will execute one SQL file, which you can use instead of echo.
For more information, try for /?.