If I wish to take an MS Sql 2008 offline or online, I need to use the GUI -> DB-Tasks-Take Online or Take Offline.
Can this be done with some sql script?
ALTER DATABASE database-name SET OFFLINE
If you run the ALTER DATABASE command whilst users or processes are connected, but you do not wish the command to be blocked, you can execute the statement with the NO_WAIT option. This causes the command to fail with an error.
ALTER DATABASE database-name SET OFFLINE WITH NO_WAIT
Corresponding online:
ALTER DATABASE database-name SET ONLINE
-- Take all user databases offline
CREATE PROCEDURE SP_TakeOfflineAllDatabase AS
BEGIN
DECLARE #db sysname, #q varchar(max);
DECLARE cur_db CURSOR FOR
SELECT name FROM sys.databases WHERE owner_sid<>0x01;
OPEN cur_db;
WHILE 1=1
BEGIN
FETCH NEXT FROM cur_db INTO #db;
IF ##FETCH_STATUS <> 0
BREAK;
SET #q = N'ALTER DATABASE [' + #db + N'] SET OFFLINE WITH NO_WAIT';
EXEC(#q);
END;
CLOSE cur_db;
DEALLOCATE cur_db;
END;
Restart the server before run the procedure. It will close the existed connections to the databases.
I know this is an old post but, just in case someone comes across this solution and would prefer a non cursor method which does not execute but returns the scripts.
I have just taken the previous solution and converted it into a select that builds based on results.
DECLARE #SQL VARCHAR(8000)
SELECT #SQL=COALESCE(#SQL,'')+'ALTER DATABASE '+name+ N' SET OFFLINE WITH NO_WAIT;
'
FROM sys.databases
WHERE owner_sid<>0x01
PRINT #SQL
Here's a note that just might be very usefull to you :
It's almost always possible to see what the GUI is doing TSQLwise behind the scenes.
c : http://www.mssqltips.com/tip.asp?tip=1505
Related
I am looking to write a stored procedure which received a database name along with other parameters, and the stored procedure needs to work on the Database which it received
any thoughts please
Something like the following should work, as long as correct permissions are setup:
CREATE PROCEDURE dbo.sptest
#DB VARCHAR(50)
AS
BEGIN
DECLARE #sqlstmt VARCHAR(MAX)
SET #sqlstmt='SELECT TOP 10 * FROM ' + #DB + '.dbo.YourTableName'
sp_executesql #sqlstmt
END
GO
As mentioned, be very careful when using dynamic SQL like this- only use with trusted sources because of the ability to wreck havoc on your DB. At a minimum, you should add some checking of the value of #DB passed in to make sure it matches a limited list of database names that it will work with.
I have problems creating schema for all databases on a sql server in one script.
declare #ssql varchar(2000)
set #ssql= 'use [?]
GO
CREATE SCHEMA [sp_schema]'
exec sp_msforeachdb #ssql
go
But I am always getting these errors:
Incorrect syntax near 'GO'.
'CREATE SCHEMA' must be the first statement in a query batch.
And if I use another statement like CREATE USER => everything works fine.
Any ideas?
Thanks.
Ok
I found it.
It should be like this:
declare #ssql varchar(2000)
set #ssql= 'use [?]
EXEC (''CREATE SCHEMA [sp_schema]'')'
exec sp_msforeachdb #ssql
go
And it works!!
Thanks Dan for your contribution!
GO is not actually a SQL Server command. It is used as a batch separator in applications like SQL Server Management Studio.
I think you can just remove the GO.
Otherwise, this should work:
declare #ssql varchar(2000);
set #ssql= '
use [?]
declare #sql varchar(100)=''create schema [sp_schema]''
exec(#sql)
'
exec sp_msforeachdb #ssql;
I am running SQL Server 2005 on Windows Server 2003 machine.
I have a requirement to accumulate small text files into a bigger one.
So I use
exec xp_cmdshell #sql
where #sql=
'copy /b'+#sourcePath+#sourceFile+' '+#destinationPath+#NewFileName
Both the source and destination paths are on a separate server.
Seldom this process fails and I don't find anything else in the event or SQL Server logs.
The Surface Area Config for xp_cmdshell is also enabled.
Please help.....
I just tested this on my sql server 2005 and EXEC dbo.xp_cmdshell always returns output (even in the case of a bogus command) in the form of a table. For C#, if you call this code with ExecuteNonQuery, then call it with ExecuteReader and read the output. Alternatively, you could dump the output in a table so that you can look at it later at your leisure. Create a table like this :
CREATE TABLE [dbo].[xp_cmdShellOutput](
[errorMsg] [nvarchar](max) NULL
)
and then use this code :
DECLARE #sql AS VARCHAR(600)
SELECT #sql = '<your command>'
INSERT dbo.xp_cmdShellOutput(errorMsg)
EXEC dbo.xp_cmdshell #sql
I am attempting to drop and recreate a database from my CI setup. But I'm finding it difficult to automate the dropping and creation of the database, which is to be expected given the complexities of the db being in use. Sometimes the process hangs, errors out with "db is currently in use" or just takes too long. I don't care if the db is in use, I want to kill it and create it again. Does some one have a straight shot method to do this? alternatively does anyone have experience dropping all objects in the db instead of dropping the db itself?
USE master
--Create a database
IF EXISTS(SELECT name FROM sys.databases
WHERE name = 'mydb')
BEGIN
ALTER DATABASE mydb
SET SINGLE_USER --or RESTRICTED_USER
--WITH ROLLBACK IMMEDIATE
DROP DATABASE uAbraham_MapSifterAuthority
END
CREATE DATABASE mydb;
We use Hudson to rebuild staging sites for our QA team all the time. We kill connections, drop the database, then restore/rebuild/remigrate a DB.
This is what I use to kill connections so I can drop a DB.
USE MASTER
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_KillDatabaseProcesses]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_KillDatabaseProcesses]
GO
CREATE PROCEDURE dbo.sp_KillDatabaseProcesses(#databaseName varchar(100))
AS
DECLARE #databaseId int,
#sysProcessId int,
#cmd varchar(1000)
EXEC ('USE MASTER')
SELECT #databaseId = dbid FROM master..sysdatabases
WHERE [name] = #databaseName
DECLARE sysProcessIdCursor CURSOR FOR
SELECT spid FROM [master]..[sysprocesses] WHERE [dbid] = #databaseId
OPEN sysProcessIdCursor
FETCH NEXT FROM sysProcessIdCursor INTO #sysProcessId WHILE ##fetch_status = 0
BEGIN
SET #cmd = 'KILL '+ convert(nvarchar(30),#sysProcessId)
PRINT #cmd
EXEC(#cmd)
FETCH NEXT FROM sysProcessIdCursor INTO #sysProcessId
END
DEALLOCATE sysProcessIdCursor
GO
Setting single user with rollback immediate is the typical way of kicking everyone out before a drop.
But I'm a bit surprised that your CI drops the DB and creates it in the same script. Normally the CI should deploy the database, using the deploy script/methods of your build deliverable, just as a customer would do it. But you can't seriously have a deployment script that drops the database on the customer deployment. Usually the CI has a step to cleanup/flatten the test server, and then run the build deliverable setup process, which will deploy the database. And you should also have a story for upgrade scenarios, perhaps using an application metadata version upgrade step.
Im using SQL Server Management Studio 2008 (ssms.exe) connected with a local SQL Server 2000, so I notice that every time I try enter on Linked Server option It crash inmediatly so I want to delete all the servers linkeds there for try again.
What script should I use or what command on T-SQL I have to run for delete all and without specifying the name of each server linked.
Thanks
You can execute sp_dropserver for all linked servers using the database cursor. The following example shows how to do this.
DECLARE #sql NVARCHAR(MAX)
DECLARE db_cursor CURSOR FOR
select 'sp_dropserver ''' + [name] + '''' from sys.servers
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #sql
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC (#sql)
FETCH NEXT FROM db_cursor INTO #sql
END
CLOSE db_cursor
DEALLOCATE db_cursor
I think you can only delete on linked server at a time, using sp_dropserver:
http://msdn.microsoft.com/en-us/library/ms174310.aspx
You could call sp_linkedservers
http://msdn.microsoft.com/en-us/library/ms189519.aspx
reading the returned list into a temporary table, and then loop through that table, calling sp_dropserver for each element.
While connected to the server:
select 'exec sp_dropServer ''' + name + '''', * from sys.servers where is_linked = 1
run the outputted first column. win.
This also allows you to pick and choose which server you want to get rid of. It is probably hanging on the connection, getting garbage it doesn't know how to handle back from a server, or a corrupted link driver.
You can't just arbitrarily delete all the linked servers from every server. You'll have to (at a minimum) open a connection to each server and run some form of script or command for each linked server. If you want to know how to write a script to drop all linked servers, I suggest that you start by looking at sp_linkedservers and sp_dropserver.
Do you get any error message when it is crashing?
Also what is the service pack of that corresponding SQL 2000 server?
I would rather fix this tools issue than simply recreating them a fresh.
Version without a cursor. server_id=0 is the local server not a linked server.
--remove all linked servers
declare #sql nvarchar(max)
while exists (select 1 from sys.servers where server_id>0)
begin
select #sql= N'sp_dropserver ' + [name] from sys.servers where server_id>0
exec (#sql)
end