assign DB name to some varibale while executing script using CMD - sql

I have more than 1 sql scripts. I want to execute them using only 1 SQLCMD line instead of writing separate SQLCMD line for each script. There's a way where i can create a new .sql file and by using :r . I just need to assign a sql script name in-front :r but the scripts which i am going to execute refers to more than one DB. I prepared the following script but its not working as expected:
Script-1
INSERT INTO [$(dbuser1)].[dbo].[A](Name)
VALUES('Tod')
INSERT INTO [$(dbuser2)].[dbo].[B]( Name )
VALUES ('John')
Script-2
INSERT INTO [$(dbuser1)].[dbo].[A]( Email )
VALUES('tod#gmail.com')
INSERT INTO [$(dbuser2)].[dbo].[B]( Email )
VALUES ('john#gmail.com')
Script-3
SET NOCOUNT ON
SET NOEXEC OFF
-- Quit when error.
:On Error Exit
-- SQLCMD Variables
:setvar dbname1 TestDatabase1
:setvar dbname2 TestDatabase2
:r Script-1.SQL
:r Script-2.SQL
and CMD Line
sqlcmd -S <Serevrname> -i <Script-3 path>
is it a correct way by assigning DB name to variable?

Related

SQL Server database project pre- and post-deployment script

I've added an extra column to a table which I want to initialize using a query in the post deployment script. Unfortunately I can't seem to write a query which can be run every time so I'm looking for a way to check in the pre-deployment script if the column is available and pass an argument or variable to the post-deployment script which will then run the initialization query once.
Attempt 1: I tried setting a sqlcmd var in the pre-deployment script but the following syntax isn't allowed:
IF COL_LENGTH('dbo.Table','NewColumn') IS NULL
:setvar PerformInitQuery 1
Attempt 2: I've also tried using a normal variable in the pre-deployment script:
DECLARE #PerformInitQuery BIT = 0
IF COL_LENGTH('dbo.Table','NewColumn') IS NULL
SET #PerformInitQuery = 1
And accessing it in the post-deployment script:
IF #PerformInitQuery = 1
BEGIN
:r ".\DeploymentScripts\PerformInitQuery.sql"
END
This last attempt seemed to work when publishing the project from Visual Studio but not on our build server; which uses SqlPackage.exe to publish the generated .dacpac file to the database.
Error SQL72014: .Net SqlClient Data Provider:
Msg 137, Level 15, State 2, Line 12
Must declare the scalar variable "#PerformInitQuery"
You could try using a temp table to hold values you wish to pass from pre to post scripts;
/*
Pre-Deployment Script Template
--------------------------------------------------------------------------------------
This file contains SQL statements that will be executed before the build script.
Use SQLCMD syntax to include a file in the pre-deployment script.
Example: :r .\myfile.sql
Use SQLCMD syntax to reference a variable in the pre-deployment script.
Example: :setvar TableName MyTable
SELECT * FROM [$(TableName)]
--------------------------------------------------------------------------------------
*/
select 'hello world' as [Col] into #temptable
picked up in post deployment script;
/*
Post-Deployment Script Template
--------------------------------------------------------------------------------------
This file contains SQL statements that will be appended to the build script.
Use SQLCMD syntax to include a file in the post-deployment script.
Example: :r .\myfile.sql
Use SQLCMD syntax to reference a variable in the post-deployment script.
Example: :setvar TableName MyTable
SELECT * FROM [$(TableName)]
--------------------------------------------------------------------------------------
*/
declare #var nvarchar(200)
select #var = [Col] from #temptable
print #var
hello world
Update complete.

How to pass a query stored in a variable to a sql file. Shell script

I am creating a shell script where I have saved entries from a text file into an array. Those values are properly stored and show the correct contents. One of those entries contains a simple query and I want to pass it to a sql file. With that sql query I want to save the results into a text file.
Here is the part of the code that calls the sql file to run the sql script
PURGE_SITES=purge_site.txt
logmsg "USERID - $PURGES_SITE" n
QUERY=${Unix_Array[4]}
echo $QUERY
sqlplus -s $USER/$PASS <<EndSQL
#purges_sites.sql $PURGE_SITES '$QUERY'
EXIT SQL.SQLCODE
EndSQL
for now query stored in ${Unix_Array[4]} is "select -1 from dual"
Here is the file contents of the .sql file
set echo off ver off feed off pages 0
accept fname prompt 'Loading Sites...'
spool &1;
&2
/
spool off
It gives me error and reads &2 as "&2" instead of the query saved in the variable. However when i edit the .sql file and add something beforehand, it will display the correct data from the variable.
Here is the output
select -1 from dual
File Name===> results.txt
select -1 from dual
Loading Sites...SP2-0042: unknown command "&2" - rest of line ignored.
SP2-0103: Nothing in SQL buffer to run.
Here is the output if I add something before &2.
select -1 from dual
File Name===> results.txt
select -1 from dual
Loading Sites...select * from table_table select -1 from dual
*
ERROR at line 1:
ORA-00933: SQL command not properly ended
I typed in select * from table_table before &2.
So its actually retrieving the value from the variable but something needs to come beforehand in order to pass correctly.
Is there a system execute command in oracle that will execute a query? &2 just by itself is not allowed.
Wont this help you?
PURGE_SITES=purge_site.txt
logmsg "USERID - $PURGES_SITE" n
QUERY=${Unix_Array[4]}
echo $QUERY
# FRAME YOUR QUERY, PROMPTING USER IN SHELL ITSELF AND SEND TO SQLPLUS DIRECTLY
# BEWARE SQL INJECTION POSSIBLE
# YOU CAN REDIRECT THE SQLPLUS OUTPUT TO A FILE LIKE THIS, NO SPOOL NEEDED
sqlplus -s $USER/$PASS <<EndSQL >> $OUTPUT_FILE
set echo off ver off feed off pages 0
$QUERY
/
EXIT SQL.SQLCODE
EndSQL

Syntax error in SQLCMD SQL script?

I'm currently trying to get a SQL script working for SQL Server 2005. I'm using SQLCMD to execute the script and it fails giving me an "Error: Syntax error at line 7 near command ':r'" error.
The script:
--Main Script--
SET NOCOUNT ON
GO
:on error exit
:r C:\Documents and Settings\ZSmith\My Documents\Scripts\CreateDatabase
:r C:\Documents and Settings\ZSmith\My Documents\Scripts\CreateTables
I can provide the other SQL scripts if needed but they function fine on their own. I'm just trying to automate the entire process.
From what I know, you need to
put the SQL file name into double quotes - especially if the path contains spaces!
include the .sql extension on the file name
Try this:
:r "C:\Documents and Settings\ZSmith\My Documents\Scripts\CreateDatabase.sql"
:r "C:\Documents and Settings\ZSmith\My Documents\Scripts\CreateTables.sql"

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

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

Executing a stored proc inside a script file using the sqlcmd -i

Need some help with script files.
I have an SQL script file in the following format:
Begin tran
insert..
select..
update..
Commit
exec linked_server.db1.dbo.storedproc1
I am calling the above script file from within a .js file in the following manner:
var sCommand = "sqlcmd -i C:\\scriptfile1"
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec(sCommand);
When I run the .js file, the code between tran-commit gets executed but the storeproc1 is never called. I know for sure that the storedproc1 is not called because it has a list of insert statements that never shows up in the table.
Have you tried running the exec storedproc1 alone? Maybe it throws an error.
Also you can try adding go like this:
commit
go
exec storedproc1
You can try this in the management studio first. After you are sure it works in the management studio, you can go on running it through sqlcmd.
Edit: next you can check the permission of the user running the script, whether it is allowed to run stored procedure.