How to use sqlcmd to create a database - sql-server

I have a .sql script and I want to build a database from it. How to do it in sqlcmd? I know it's like:
CREATE DATABASE dbName
GO
But how to specify the .sql script and location to build the database?

Use #Jeremiah Peschka's answer to supply the sqlcmd utility with the script to execute.
As for the location for the newly created database, it can be specified as part of the CREATE DATABASE command:
CREATE DATABASE dbName
ON (
NAME = dbName_dat,
FILENAME = 'D:\path\to\dbName.mdf'
)
LOG ON (
NAME = dbName_log,
FILENAME = 'D:\path\to\dbName.ldf'
)
As you can see from the linked article, you can specify other properties as well, like initial size, maximum size etc.

This is very simple. Just enter following command to run sqlcmd:
sqlcmd -U sa -P password
Then enter:
CREATE DATABASE MYDB
GO
This will create the db. Then enter "quit" to exit.

without a file:
sqlcmd -Q "CREATE DATABASE HelloWorld"

sqlcmd -i C:\path\to\file.sql
More options can be found in SQL Server books online.

use this:
sqlcmd -i "c:\my scripts\my script.sql"
see sqlcmd description at MS for other options

Related

Complete novice question: I want to delete a table via command prompt (postgis)

I am a regular FME user and I know how to create a postgis database to be used in FME (using PGadmin). I now want to use FME to backup and then delete a generated table. I use the 'systemcaller' transformer for this, the systemcaller basically opens command prompt.
I was able to make a backup file using cd C:\Program Files\PostgreSQL\118\bin\ && set PGPASSWORD=password&& pg_dump.exe -U postgres -p 5433 -d bag -t tablename -F c -f C:/Users/username/Downloads/tablename.backup", but I am having a hard time getting the table to be deleted.
I tried the 'drop table' command, but this is not recognized. It will recognize drobdb, but I obviously do not want to drop the whole database.
What commandline should I use to drop te table 'testtable' in the database 'testdatabase'?

How to run a sql command from the command prompt in a batch file

I'm looking for a simple way to run the following command from a command line. I need to run it as part of a regular old .bat file on a windows server, so I need some kind of command line utility. I looked into sqlcmd but not sure on the correct syntax and it somewhat looked complicated. I need to be able to enter a sql username and password as part of the utility to connect to the sql server, since this will be running on a different machine.
I need to run a simple command like this:
UPDATE ABC SET PictureName = ID + '.jpg' WHERE TYPE = 'active'
Ideally I would want some tool that I can simply run in this way or something similar:
AwesomeTool.exe -sqlUsername "username" -sqlPass "password" -sqlStatement "UPDATE ABC SET PictureName = ID + '.jpg' WHERE TYPE = 'active'"
By the way this needs to work in MS SQL 2008 and newer. Thank you.
Just use sqlcmd:
sqlcmd -U "username" -P "password" -S MySqlServer -d MyDatabase -q "UPDATE ABC SET PictureName..."

SQL - Automatic results to CSV or Text File

I was wondering if anyone can help.
I have a number of queries in SQL (all in separate *.sql files). I wanted to know if there is a way to run these queries automatically or mass run them to be saved to either a csv or txt file?
Also, I have come variables within these queries which will need to be amended on a weekly bases before the queries are run.
Thanks.
KJ
Could you please provide some additional help in relation to the variables? Previously I would declare and set variables as:
DECLARE #TW_FROM DATETIME
DECLARE #TW_TO DATETIME
SET #TW_FROM = '2015-11-16 00:00:00';
SET #TW_TO = '2015-11-22 23:00:00';
How do I do this using sqlcmd?
Yes, you can use sqlcmd to do this.
First of all - variables. You can refer to your variables in the .sql files using $(variablename) wherever you want to substitue the variable. For example,
use $(dbname);
select $(columnname) from table1 where column= '$(var1)'
You then call sqlcmd with the following command (note the argument -v variables)
sqlcmd -S servername -d database -i "yoursqlfile.sql" -v dbname="database" columnname="column" var1="Fred"
In order to output this to a file, you tag > filename.txt on the end
sqlcmd -S servername -d database -i "yoursqlfile.sql" -v dbname="database" columnname="column" var1="Fred" > filename.txt
If you want to output to a csv, you can also specify the delimiter using the argument -s (note the idfference with the capital S for server). So now we have
sqlcmd -S servername -d database -s "," -i "yoursqlfile.sql" -v dbname="database" columnname="column" var1="Fred" > filename.csv
If you want to output several commands to the same csv or txt file, use >> instead of > as it add to teh bottom of the file, rather than replacing it.
sqlcmd -S servername -d database -s "," -i "yoursqlfile.sql" -v dbname="database" columnname="column" var1="Fred" >> filename.csv
To run this for several scripts, you can put the statements in a batch file, and then change the variables every week.
You could write a batch file that uses sqlcmd:
MSDN sqlcmd
That will allow you to call script files in a loop and output the results to a file.
Convert your current scrips to a Stored Procedure.
You can then pass your variables to that and run the query.
If you have SQL Server agent available (SQL standard or better) you can use this to automate the running of the stored procedures.
Otherwise the same can be achieved with Task Scheduler in windows.
As for exporting to CSV this will be useful.
It depends on where your SQL Server is acutally running. It might be quite tricky to write anything to the location you want.
You could read about BCP.
My suggestion is:
Create an UDF (best is inline-UDF!) from all of your queries within your database. Than call them from EXCEL or any other fitting product. You might want to set up an Excel where all your queries are filled one on each Sheet automatically

Add a date to output filename using SQLCMD from within SQL Agent CmdExec?

I want to run a weekly extract from a SQL Server database using SQLCMD under SQL Agent. Because I need to save multiple extracts in the same share, I want to use the current date as part of the extract's file name. When doing this from the command line, I use:
sqlcmd -S POC -i "\\org-data\data\dept\share\registry\SQLCMD\extractdata.sql" -s "|" -W -h-1 -o "\\org-data\data\dept\share\registry\Extracts\extractdata.%date:~-4,4%%date:~-10,2%%date:~-7,2%.txt"
and it works perfectly.
When I place the same statement into a CmdExec under SQL Agent, my date becomes a syntax error -- ("The filename, directory name, or volume label syntax is incorrect")
How do others handle this? Thanks.
Try using the SQL Server Agent tokens. They are described in MSDN article, "Use Tokens in Job Steps". The DATE token provides the current date in YYYYMMDD format. For your example use:
"...\Extracts\extractdata.$(ESCAPE_DQUOTE(DATE)).txt"
This isn't working for me
echo off
sqlcmd -m 1 -S 10.108.96.210\QA832 -U Exception -P Password1 -i E:\KCM_UAT\Exception.sql -o C:\Test_$(ESCAPE_DQUOTE(DATE)).txt -W -h-1 -s " "
set /p delExit=Press the ENTER key to exit...:
The file is written out like this
Test_$(ESCAPE_DQUOTE(DATE)).txt

Setting up a database, schemas, tables and stored procedures all in one click

I have all the scripts to do:
Set up a database.
Create schema/s.
Create tables.
Create stored procedures.
I would like to write a batch file that will have SQL Server run those scripts and consequently my database will be created easier and quicker. For the sake of this example, lets assume that I have a folder with the address C:\folder and inside this folder I have files SetDatabase.sql, SetSchema.sql, SetTable.sql, and SetSP.sql. How would I set all that up on localhost\TSQL2012?
You can do this in powershell using sqlcmd
sqlcmd -S serverName\instanceName -i scripts.sql
The above statement will execute a script.
You can use the :r command in another file (scripts.sql) to store all your scripts.
:r C:\..\script1.sql
:r C:\..\script2.sql
....
set _connectionCredentialsMaster=-S MyServer\MyInstance -d Master -U sa -P mypassword
set _connectionCredentialsMyDatabase=-S MyServer\MyInstance -d MyDatabase -U sa -P mypassword
set _sqlcmd="%ProgramFiles%\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE"
%_sqlcmd% -i MyFileCreateDatabase001.sql -b -o MyFileCreateDatabase001.Sql.log %_connectionCredentialsMaster%
%_sqlcmd% -i MyFile001.sql -b -o MyFile001.Sql.log %_connectionCredentialsMyDatabase%
%_sqlcmd% -i MyFile002.sql -b -o MyFile002.Sql.log %_connectionCredentialsMyDatabase%
set _connectionCredentialsMaster=
set _connectionCredentialsMyDatabase=
set _sqlcmd=
Just remember, when you run the 'Create Database' statement, you are actually USING the "Master" database. Then, after MyDatabase is created, you can use it. Thus why the first line in the example above...connects to Master.
The above will let you set the credentials "at the top" "one time"....and keep your lines in the file for each file.
Use SQL data tools to implement your needs. You should study about that before you do.
http://msdn.microsoft.com/en-in/data/tools.aspx

Resources