Posted on Leave a comment

Default Database

/***********************************************
* This gives users a dummy default database
* in order to prevent them from:
* 1) having ‘master’ as a default database
* 2) not being able to connect to the server
* because their default database has been
* dropped, recreated, or restored
***********************************************/

USE master
GO

IF NOT EXISTS ( SELECT TOP 1 1 FROM sysdatabases WHERE name = ‘uno’ )
BEGIN
CREATE DATABASE [uno]
END
GO

ALTER DATABASE [uno] SET READ_WRITE
GO

USE uno
GO

GRANT SELECT TO [public]
GO

DECLARE @name sysname
, @sql nvarchar(max)

DECLARE login_cur CURSOR FAST_FORWARD FOR
SELECT name
FROM master..syslogins WITH (NOLOCK)
WHERE upper(name) LIKE ‘%’

OPEN login_cur

FETCH login_cur INTO @name

WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = ‘IF NOT EXISTS ( SELECT TOP 1 1 FROM sysusers WHERE name = ”’ + @name + ”’ ) ‘
SET @sql = @sql + ‘CREATE USER [‘ + @name + ‘] FOR LOGIN [‘ + @name + ‘] WITH DEFAULT_SCHEMA=[dbo];’
EXEC sp_executesql @sql
SET @sql = ‘ALTER LOGIN [‘ + @name + ‘] WITH DEFAULT_DATABASE=[uno];’
EXEC sp_executesql @sql
FETCH login_cur INTO @name
END

CLOSE login_cur
DEALLOCATE login_cur
GO

–ALTER DATABASE [uno] SET READ_ONLY
–GO

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.