I have a sql file that I do not understand.
What does :out in the below code means?
This is not usual sql code, where can I learn about this script command?
Thanks!
USE [DATABASE_A]
GO
:out D:\xxx\xxxxxx.csv
exec sp_xxxx
go
It is a sqlcmd script:
By using the Database Engine Query Editor in SQL Server Management Studio you can write and edit queries as SQLCMD scripts. You use SQLCMD scripts when you have to process Windows System commands and Transact-SQL statements in the same script.
:out <filename>|stderr|stdout
The following example uses a sqlcmd statement to create an output file called testoutput.txt, executes two Transact-SQL SELECT
:out C:\testoutput.txt
SELECT ##VERSION As 'Server Version'
--- ...
It looks like a command that will be processed by SQLServer Management Studio to save the query results to the named file. It's not a part of the SQL standard, it's particular not only to SQLServer but specifically the SSMS query tool. You couldn't write this in another SQLServer query tool and guarantee it would work
Related
I have a SQL Server database set up that I manage using SQL Server Management Studio 17.
In that database, I have 27 tables that I maintain by running pretty simple OPENQUERY scripts every morning, something to the effect of:
DROP TABLE IF EXISTS [databasename].[dbo].[table27]
SELECT * INTO [databasename].[dbo].[table27] FROM OPENQUERY(OracleInstance, '
SELECT
table27.*
FROM
table27
INNER JOIN table26 ON table27.criteria = table26.criteria
WHERE
< filter >
< filter >
');
And this works great! But, it is cumbersome to every morning, sign into SSMS, and right click on my database and hit "New Query" and copy in 27 individual SQL scripts and run them. I am looking for a way to automate that. My directory that holds these scripts looks like this:
I don't know if this is achievable in SSMS or in like a batch script. I would imagine for the latter, some pseudocode looking like:
connect to sql server instance
given instance:
for each sql_script in directory:
sql_script.execute
I have tried creating a script in SSMS, by following:
Tasks -> Script Database ->
But there is no option to execute a .sql file on the tables in question.
I have tried looking at the following resources on using T-SQL to schedule nightly jobs, but have not had any luck conceiving of how to do so:
https://learn.microsoft.com/en-us/sql/ssms/agent/schedule-a-job?view=sql-server-2017
Scheduled run of stored procedure on SQL server
The expected result would be the ability to automatically run the 27 sql queries in the directory above to update the tables in SQL Server, once a day, preferably at 6:00 AM EST. My primary issue is that I cannot access anything but SQL Server Management Studio; I can't access the configuration manager to use things like SQL Server Agent. So if I am scheduling a task, I need to do so through SSMS.
You actually can't access the SQL Server Agent via Object Explorer?
This is located below "Integration Services Catalog"
See highlighted below:
You describe not being able to access that in the question for some reason. If you can't access that then something is wrong with SQL Server or perhaps you don't have admin rights to do things like schedule jobs (a guess there).
In SSMS you would wnat to use Execute T-SQL Statement Task and write your delete statement in the SQL Statement field in the General Tab.
However, I would look at sqlcmd. Simply make a batch script and schedule it in Task Scheduler (if you're using windows). Or you could use
for %%G in (*.sql) do sqlcmd /S servername /d databaseName -E -i"%%G"
pause
From this post. Run all SQL files in a directory
So basically you have to create a Powershell script that calls and execute the sql scripts.
After that you can add your Powrshell script to the Task Scheduler.
I suggest you add these scripts as jobs for the SQL Server Agent.
I want to run batch file from SQL Job without using exec xp_cmdshell.
Any idea?
Thanks
You could use a SQL Server Job, otherwise i cannot think of a way you could without xp_cmdshell.
Take a look at this
I want to run batch file from SQL Job without using exec xp_cmdshell.
Any idea?
Worth to mention that you can also leverage SQLCLR.
Example: CLR Stored procedure to execute command
Some other googlable threads:
How to execute a DOS command when xp_cmdshell is disabled in SQL Server
Executing an external process() in SQLCLR Project
Such approach introduces severe risks like memory leaks, crashing of underlying .net app pool etc
Therefore another link: Security in the CLR World Inside SQL Server
Instead of running batch file, i have created power shell and ran it from SQL job. It satisfy my requirement and resolved my issue.
Do it like the picture: like this image.
The drive containing the batch file should be other than the C drive, to avoid trouble.
Add execute, read and write permissions for the user, which you are using to run the batch file, to get the username run this query: EXEC master..xp_cmdshell 'whoami', get the name after the \ sign. For example "nt service\mssqlserver". Add permission for this user: mssqlserver
Finally make sure you put the batch file on the same server as where you execute your Job.
We have several SQL scripts which are generated from an Entity Model. They need to be run in a specific order. Additionally there are several filling scripts which insert test data into the database.
Currently I need to open each script in Visual Studio and execute them in the correct order by clicking Execute (ctrl shift E).
Is there a way to create a script like Master.sql that contains includes like this:
BEGIN TRANSACTION
ImportOrInclude myDB1.sql
ImportOrInclude myDB2.sql
...
COMMIT
This is only required to run from Visual Studio and will not be part of the application itself.
How can this be done?
EDIT 1
I've found that there is something called SQLCMD Scripts which can import SQL files:
http://msdn.microsoft.com/en-us/library/aa833281%28v=vs.80%29.aspx
But my question is then how to get the directory path of the current solution into the :r command.
EDIT 2
So I figured out how to do it, not perfectly, but it works. The downside is that the $(SolutionDir) is not loaded from the Visual Studio variables, so you need to set it up manually. This code is meant to be run in Visual Studio:
-- turn on in menu: Data -> Transact SQL editor -> SQL CMD mode
-- set this to path where the .sln file is.
:setvar SolutionDir C:\_work\projectname\
:!! echo $(SolutionDir)Maa.EntityModel.All\DbWEntityModel.edmx.sql
:r $(SolutionDir)Maa.EntityModel.All\DbWEntityModel.edmx.sql
go
:!! echo $(SolutionDir)Maa.EntityModel.All\DblQEntityModel.edmx.sql
:r $(SolutionDir)Maa.EntityModel.All\DbQEntityModel.edmx.sql
go
Use sqlcmd utility.
Extract you might find interesting:
-i input_file[,input_file2...]
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. Do not use any spaces between file names. sqlcmd will first check to see whether all the specified files exist. If one or more files do not exist, sqlcmd will exit.
Example:
sqlcmd -dDataBaseName -E -Stcp:ServerName\instancename -imaster.sql
Master.Sql:
:r file1.sql
:r file2.sql
Use the Business Intelligence Development Studio that comes with SQL Server to do this. Create a new SSIS Package. Inside this package create several Execute SQL Tasks in the Control Flow for each file you have and set SQLSourceType to FileConnection and choose your file.
Executing the following script via sqlcmd fails. However, executing it via ssmo or SQL Server Management Studio works.
sqlcmd -S . -d test -i input.sql
input.sql:
CREATE FUNCTION test()
RETURNS #t TABLE ("ID" INT)
AS
BEGIN
RETURN
END
Even when I put SQL Server Management Studio into sqlcmd mode, it still fails. This is a problem as we test our scripts with SSMS, but deploy with SQLCMD. Thus we only find out our code doesn't work when we attempt to deploy.
Why does sqlcmd behave like this? Is there any way to turn it off?
If you really need to use double quotes to delimit identifiers in your scripts, you'd need to set the quoted_identifier option on SQLCMD by using the -Ienable switch. It is OFF by default in SQLCMD but ON by default in SSMS, which is why your tests work in SSMS.
Read more about QUOTED_IDENTIFIER here.
Use square brackets for this: [ID]
Is it possible to enter a command line command (like in a batch file) to attach a detached database to SQL Server, in stead of opening the management studio and doing it in there?
you need to use: sqlcmd Utility
The sqlcmd utility lets you enter
Transact-SQL statements, system
procedures, and script files at the
command prompt, in Query Editor in
SQLCMD mode, in a Windows script file
or in an operating system (Cmd.exe)
job step of a SQL Server Agent job.
This utility uses OLE DB to execute
Transact-SQL batches.
Then use CREATE DATABASE (Transact-SQL) to do the attach and sp_detach_db (Transact-SQL) to do the detach. The sp_attach_db (Transact-SQL) is going to be removed in a future version of Microsoft SQL Server.
If you need to specify the log file name: USE master; GO; CREATE DATABASE DBNAME ON ( FILENAME = 'C:\DBFILE.mdf') LOG ON ( FILENAME = 'C:\DBLOGFILE_log.ldf') FOR ATTACH; GO; And to detach: USE master; GO; EXEC sp_detach_db 'DBNAME', 'true'; GO;
Small gotcha, it won't tell you what is wrong when using sqlcmd and your mdf/ldf files are marked read-only. Make sure they are read-write.