Msg 102, Level 15, state 1 Line 1 Incorrect syntax near 'n' - sql

I have the following query which I am running using a batch file. In the batch file I use the following syntax:
echo populating Application table with values...
SET "installFile=%sqlDir%\Install\DataFiles\Insert_ApplicationNames.sql"
OSQL /n /i "%installFile%" /d%db% /U%user% /P%pswd% /S%serv%
echo
echo populated Application table with values in Insert_ApplicationNames.sql
echo
The sql shown below runs without any errors when executed from the SQL Management Studio, but it keeps erroring out when run as a part of the batch script. Could some one help me find what I may be doing wrong here?
Also, the rows do get inserted, but our nightly QA install breaks because of the error thrown by the batch script.
IF NOT EXISTS(SELECT * FROM Application WHERE name = '')
BEGIN
INSERT INTO Application
(Name)
VALUES
('')
END
GO
IF NOT EXISTS(SELECT * FROM Application WHERE name = 'App1.exe')
BEGIN
INSERT INTO Application
(Name)
VALUES
('App1.exe')
END
GO
IF NOT EXISTS(SELECT * FROM Application WHERE name = 'App2.exe')
BEGIN
INSERT INTO Application
(Name)
VALUES
('App2.exe')
END

GO is the (default) batch separator keyword in Management Studio, but it isn't a real SQL keyword (i.e., SQL Server doesn't recognize it).
Remove those from your script -- in the script you've provided, they are irrelevant anyway -- and you should be good to, um, go.

Curious whether your variables should be right up against the switches. Try this?
OSQL -n -i "%installFile%" -d %db% -U %user% -P %pswd% -S %serv%
What happens when you use the line above with your known good values right in the command?
OSQL -n -i "C:\foo.sql" -d MyDB -U MyUser -P MyPwd -S MyServ

Related

Unable to pass in parameters to SQL Server Stored procedure from Windows batch script

I tried searching for the solution here but didn't find one that can solve my problem. I have following batch script:
for /f "tokens=1-3 delims=, " %%a in ('\path\batch_output.txt') do (
echo %%a, %%b, %%c
sqlcmd -S server -E -i path\spu_update_src_trg_ref.sql -v SourceName= %%a Instancname= %%b exitcode= %%c
ping 1.1.1.1 -n 1 -w 5000 > nul
)
Inside spu_update_src_trg_ref.sql I have below code:
use dbname
go
EXEC dbo.spu_update_src_trg_ref $(SourceName), $(Instancname), $(exitcode)
I am running the below batch script via a job scheduler so unable to see the direct error in the cmd. But my job is getting failed and the stored proc is also not getting executed. If need, stored proc is as below:
CREATE PROCEDURE dbo.spu_update_src_trg_ref
#SourceName VARCHAR(100),
#Instancname VARCHAR(100),
#exitcode INT
AS
BEGIN
IF #exitcode=0
BEGIN
UPDATE dbo.t_ctrm_ref_src_trg SET LoadStatus='Completed' WHERE SourceTableName=#SourceName;
UPDATE dbo.t_ctrm_instance_status SET InstanceStatus='Completed' WHERE InstanceName=#Instancname;
END
END
Its a simple sp that updates two tables, but I am unable to pass the input parameters from batch script. Please advice.
Update:
Thanks everyone for the help. I just removed some spaces and quotes('') from '\path\batch_output.txt' and it worked just fine. Appreciate all your help
There are syntax errors in your sqlcmd command. Remove the spaces between the var name, the equal sign, and the value in the "-v" portion.

SQL Server :query for exporting to file

I'm trying to learn the basics of sql programming, I am working with SQL Server 2014. I have managed to import a file into a table with the command:
BULK INSERT Db.dbo.Co2_table
FROM 'd:\dataset_co2.txt'
with
(
FIRSTROW =2,
ROWTERMINATOR ='\n'
)
GO
I would like to do the dual operation, that is exporting the content of a table to a file. I have tried:
SELECT *
INTO OUTFILE 'C:\datadump\sqldbdump.txt"
FROM dbo.alarms_2_2014
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';
bcp Db.dbo.Co2_table out "C:\users\ws5.en-cre\desktop\prova.txt" -T –c
sqlcmd -S . -d Db -E -s, -W -Q "SELECT * FROM dbo.Co2_table" > ExcelTest.csv
But none of these seem to work (I get error messages). Any idea?
I suspect you are running those commands from Management Studio. You should use console for this command.This works for me. Also check if you have permissions on that folder.
bcp "select * from Db.dbo.Co2_table" queryout C:\users\ws5.en-cre\desktop\prova.txt -c -T
or
bcp Db.dbo.Co2_table out C:\users\ws5.en-cre\desktop\prova.txt -c -T
Also you have suspicious symbol in c parameter -T –c. It is not a regular dash -.
Thank you for you answers and suggestions, and apologies for my lack of precision and my late reply (in this case I missed the notifications from stackoverflow).
Regarding the question on whether I use mstudio or console, what I do is clicking on “new query” from mstudio, write the code and press execute. So I guess the answer is that I use mstudio.
If I try:
bcp "select * from Db.dbo.Co2_table" queryout
C:\users\ws5.en-cre\desktop\prova.txt -c –T
it says
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'queryout'.
I guess in this case one of the problem is that the quotes are missing, but even adding them doesn’t solve the problem.
I am looking for a solution that can be implemented as a script. I am familiar with excel vba macros, I would like to implement something like that.
Thanks,
Alex

Error testing and control from DOS

I'm running DOS 6.0.6002 on a windows server enterprise system, SP2.
SQL Server 2008 R2 (10.50.4000)
I have a main control program in DOS.
I'm invoking an sql program through sqlcmd.
A simplified version looks like this:
set sqlsvr=myServer
set logfile=logfile.txt
sqlcmd -S %sqlsvr% -d myDB -i import_some_stuff.sql > "%logfile%" 2>&1
echo error level = %ERRORLEVEL%
I need this program to be pretty robust. It has to run every day against a lot of files and tables. If it fails, I need to catch it and notify sysadmin. For now, just catch it.
So to test this, I've tried the following tests:
1) Renaming the file to one that does not exist.
Result: it returns and errorlevel of 1 (that is it caught the error!) bravo!
2) typing in some syntactical rubbish at the front of the sql program.
Result: it prints the error message in the log file, BUT it DOES NOT return an error (so the return value in %ERRORLEVEL% is zero. This seems incredible to me. What am I missing?
Try the -b option to sqlcmd:
-b
Specifies that sqlcmd exits and returns a DOS ERRORLEVEL value when an
error occurs.
The value that is returned to the DOS ERRORLEVEL
variable is 1 when the SQL Server error message has a severity level
greater than 10; otherwise, the value returned is 0. If the -V option
has been set in addition to -b, sqlcmd will not report an error if the
severity level is lower than the values set using -V. Command prompt
batch files can test the value of ERRORLEVEL and handle the error
appropriately. sqlcmd does not report errors for severity level 10
(informational messages).
If the sqlcmd script contains an incorrect comment, syntax error,
or is missing a scripting variable, ERRORLEVEL returned is 1.
Here is the documentation

Return a scalar query result into a batch file variable

I would like to perform a scalar database query and return the result into a variable in a batch file.
How would one do this? The closest I example in our system that I see is if I return an exit code based on a scalar query result.
Z:\SQL2005\90\Tools\Binn\sqlcmd -S servername -dCLASS -E -Q "EXIT(select case run_type when 'Q' then 200 else 100 end from cycle_date where cycle = '1')">NUL
if %errorlevel% == 200 call %SQLSERVER%
QRTLY.BAT
if %errorlevel% == 100 call %SQLSERVER%
MTHLY.BAT
Can someone help me with the syntax?
Here's some sqlcmd help info:
-v var = value[ var=value...]
Creates a sqlcmdscripting variable that can be used in a sqlcmd script. Enclose the value in quotation marks if the value contains spaces. You can specify multiple var="values" values. If there are errors in any of the values specified, sqlcmd generates an error message and then exits.
sqlcmd -v MyVar1=something MyVar2="some thing"
sqlcmd -v MyVar1=something -v MyVar2="some thing"
-x disable variable substitution
Causes sqlcmd to ignore scripting variables. This is useful when a script contains many INSERT statements that may contain strings that have the same format as regular variables, such as $(variable_name).
How about saving it to a file without headers then reading the contents back in?
sqlcmd -S(local)\SQLExpress -dMyDatabase -Umyuser -Pmypassword -W -h -1 -Q "SELECT Top 1 MyValue FROM MyTable" -o sqlcmdoutput.txt
set /p x= <sqlcmdoutput.txt
del sqlcmdoutput.txt
echo My scalar value is %x%
I use this in a batch file. It returns the LogicalFilename for a SQL Server Database data file. This only works if there is one data file in the DB.
So the result is the environment variable DATABASEFILENAME is set to say AdventureWorks_Data.
FOR /F "usebackq tokens=1" %%i IN (`sqlcmd -w200 -h-1 -E -Q"set nocount on; Select df.name From sysdatabases as d Inner Join sysaltfiles as df on d.dbid=df.dbid Where d.name ='$(DatabaseName)' and df.Fileid =1"`) DO set DATABASEFILENAME=%%i
Have you looked at sqlcmd?

Execute SQL from file in bash

I'm trying to load a sql from a file in bash and execute the loaded sql. The sql file needs to be versatile, meaning it cannot be altered in order to make things easy while being run in bash (escaping special characters like * )
So I have run into some problems:
If I read my sample.sql
SELECT * FROM SAMPLETABLE
to a variable with
ab=`cat sample.sql`
and execute it
db2 `echo $ab`
I receive an sql error because by doing a cat the * has been replaced by all the files in the directory of sample.sql.
Easy solution would be to replace "" with "\" . But I cannot do this, because the file needs to stay executable in programs like DB Visualizer etc.
Could someone give me hint in the right direction?
The DB2 command line processor has options that accept a filename as input, so you shouldn't need to load statements from a text file into a shell variable.
This command will execute all SQL statements in the file, with newline treated as the statement terminator:
db2 -f sample.sql
This command will execute all SQL statements in the file, with semicolon treated as the statement terminator:
db2 -t -f sample.sql
Other useful CLP flags are:
-x : Suppress the column headings
-v : Echo the statement text immediately before execution
-z : Tee a copy of all CLP output to the filename immediately following this flag
Redirect stdin from the file.
db2 < sample.sql
In case, you have a variable used in your script and wanted to get it replaced by the shell before executed in DB2 then use this approach:
Contents of File.sql:
cat <<xEOF
insert values(1,2) into ${MY_SCHEMA}.${MY_TABLE};
select * from ${MY_SCHEMA}.${MY_TABLE};
xEOF
In command prompt do:
export MY_SCHEMA='STAR'
export MY_TAVLE='DIMENSION'
Then you are all good to get it executed in DB2:
eval File.sq |db2 +p -t
The shell will replace the global variables and then DB2 will execute it.
Hope it helps.