I'm having an issue with a stored procedure which SQL Server being executed as a scheduled task through Task Manager. I have a batch file containing the EXECUTE statement which is called by Task Scheduler. Platforms is SQL Server 2008 R2 on Windows Server 2008 R2.
The batch file code
#echo off
SQLCmd -S lccc-cpc-sql -E -d NTSR -Q "Execute update_vw_NTSR_Base_AllRecords_Labels_new_proc"
This SP does the following:
Drops a table
Recreates it with updated data using a SELECT INTO statement
Problem: It's running the DROP statement, but failing on the SELECT INTO. Here's what's weird though:
If I execute the sp through SSMS (right click the sp, choose Execute) OR, view a query editor, run the code to drop the table and the SELECT INTO statement, it finishes correctly. It's a very large SELECT INTO statement - hundreds of columns and about 100 joins. The purpose is to join a lot of lookup tables to values so I have one place for my users to go for labeled data and some variables computed for user friendliness. It's messy, but it's what I have to work with.
Query timeout is set to 0 (no limit). This only happened recently as I added more columns and variables but it seems it'd fail called through any method, not just through the batch file. Any thoughts on how to make this work as-is (ie without breaking this up into multiple SELECT INTO statements)?
Thanks.
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 have multiple databases on multiple servers (SQL Server 2008) with similar schema. I want to execute Stored Procedure on each of them. Right now I have to execute one by one on every server via SQL Server management studio.
Is there any possibility/option in SQL Server Management Studio that I can execute SP just once on all databases.
You can use a group query to run a script against more than one server. Look here
Then use the sp_MSForEachDB mentioned by #Ram
There are two ways I can suggest if you want to avoid doing it programmatically.
1) Use Registered Servers in SSMS. Each target database can be created as a Registered Server within a Server Group. You can then right click on the Server Group and select "New Query". This query will execute against all Registered Servers in the Group. This is explained in detail on MSSQLTips.
2) SQL Multi Script is a dedicated tool we developed at Red Gate to satisfy this use case. However, this isn't integrated into SSMS.
Using the sp_MSForEachDB stored procedure you should be able execute on multiple databases of same server.
EXEC sp_msforeachdb " IF '?' NOT IN ('DBs','to','exclude')
BEGIN
EXEC sp_whatever_you_want_to
END "
Looking around I'm sure you could write a powershell or batch script to do this but I do not have time to learn, build and test one.
So I'll do it in the language I'm happiest in: SQL and batch script
Paste the below query into SSMS and run it, substituting
Your Server List
Path to a file containing the script you want to run (i.e. replace YourSQLScript.SQL)
Path to a log file (i.e. replace YourOutputLog.TXT)
You might want to alter your script and add SELECT ##SERVERNAME to the start to log the server to your output file
WITH ServerList As (
SELECT 'Server1' ServerName UNION ALL
SELECT 'Server2' UNION ALL
SELECT 'Server3' UNION ALL
SELECT 'Server4' UNION ALL
SELECT 'Server5'
)
SELECT
'SQLCMD -S ' + ServerName + ' -E ' + ' -i C:\YourSqlScript.SQL -o C:\YourOutputLog.TXT'
From ServerList
UNION ALL
SELECT 'PAUSE'
So in this example, the file C:\YourSqlScript.SQL should probably contain something like:
SELECT ##SERVERNAME
EXEC sp_msforeachdb 'USE [?]; SELECT '?'; EXEC p_YourStoredProcedure;'
(Thanks to RAM for providing this)
(You should definitely test this script in just one database first)
Copy the output and paste into a text file. Save the text file as MyFirstBatchFile.CMD. Double click this file
Check the output file (C:\YourOutputLog.TXT)
This is not going to work first time - I just built it on the fly to show you how it can be done. If/when you get your first error, sit back take a look and see if you can solve it yourself.
If you need to do this regularly then you can have a think about how you want to automate it. For example there is a way to automate getting a list of servers (hint: SQLCMD -L)
If you are going to regularly administer multiple servers you should consider using Powershell.
In my sqlserver 2008 R2
I have a database script which generate successfully, but when I am trying to execute that script its only shows Executing query message and nothing happen.
I had waited at-lest 10 minutes for result but force fully I have to stop executing that query.
Note: All other queries are working normally, but only database script is not executing as explained above.
I doesn't know what's going on...
More details: This thisng is not happen on particular DataBase, it is make problem to all the database of my sqlserver.
Even no any single DataBase's script working, as explain below.
Its being remain to show Executing queries...
I have a large query running that loops over multiple stored procedures. Based on business rules, I'm calling the appropriate stored procedures for each record that is in my loop.
The problem is that those stored procedures sometimes generate multiple result sets. What happens then is that in SQL Server Management Studio, the 'results pane' gets filled up with data, it slows down SQL Server Management Stidion and in the end Management Studio even crashes with an out of memory exception. Is there any way in which I can suppress the results from showing up?
You can also execute it from a command line using OSQL, and specify a logfile:
osql -E -S ServerName -d DBNAme -q "EXIT(<QUERY STUFF HERE>)" -o PathtoLogFile.txt
run the query as a job in Sql Server Agent.
I created a batch file to run SqlMetal and generate Linq2Sql data classes, check into source control triggering a build, etc... I'd like to have this script run anytime there is a DDL change in Sql Server 2005.
Running the batch file via xp_cmdshell works fine outside of a trigger, like this:
exec master..xp_cmdshell 'd:\dev\db_triggers\generatedataclasses.bat', no_output
But when it runs as a trigger, it always times out connecting to the database, causing all DDL to fail. Here's my trigger:
CREATE TRIGGER [Trig_SqlMetal]
ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS
exec master..xp_cmdshell 'd:\dev\db_triggers\generatedataclasses.bat', no_output
I'm looking for advice on two points:
Make this work. For some reason it always fails when in the trigger, and doesn't when not in a trigger. Doesn't appear to be security related since it runs as LocalSystem in both cases.
Make this happen asychronously so that failures and timeouts in SqlMetal don't cause DDL update failure. I've tried wrapping the batch file with another and a "start cmd.exe /c otherbatch.bat", but when running through sql server it seems to ignore the start (works fine from DOS). I could certainly write a polling process to look at some table and pickup events, but I'd prefer this be trigger based to make it less complex (or am I doing the opposite :) ).
Your batch is probably being blocked because it tries to query data about the tables being created, but they are still locked inside a transaction (the trigger is part of the implicit transaction SQL Server starts for any DDL/DML statement), that will complete only after the trigger finishes.
The only "almost" practical way of asynchronous execution in SQL Server 2005 or higher that I know of is Service Broker. Look for "Service Broker Internal Activation".
In practice it is a bit complex to set it up properly, so you might well choose to go for the pooling option.