Create ms sql database with some flags - sql-server

I am trying to create a database through powershell. The problem I'm encountering is that I want this database to be created with some flags enabled (for example "Allow Snapshot Isolation"). I do not know how to do that and I'm having trouble finding out.
What I have done so far:
$SqlSecurePassword = $SqlServerPassword | ConvertTo-SecureString -asPlainText -Force
$Connection = new-Object Microsoft.SqlServer.Management.Common.ServerConnection("(local)", $SqlServerUser, $SqlServerPassword)
$Server = new-Object Microsoft.SqlServer.Management.Smo.Server($Connection)
$Db = new-Object Microsoft.SqlServer.Management.Smo.Database($Server, $DatabaseName)
$Db.Create()

I would wirte a SQL-Script to create the database, just like this:
CREATE DATABASE [test]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'test', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\test.mdf' , SIZE = 5120KB , FILEGROWTH = 1024KB )
LOG ON
( NAME = N'test_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\test_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)
GO
ALTER DATABASE [test] SET COMPATIBILITY_LEVEL = 120
GO
ALTER DATABASE [test] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [test] SET ANSI_NULLS OFF
GO
ALTER DATABASE [test] SET ANSI_PADDING OFF
GO
ALTER DATABASE [test] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [test] SET ARITHABORT OFF
GO
ALTER DATABASE [test] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [test] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [test] SET AUTO_CREATE_STATISTICS ON(INCREMENTAL = OFF)
GO
ALTER DATABASE [test] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [test] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [test] SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [test] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [test] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [test] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [test] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [test] SET DISABLE_BROKER
GO
ALTER DATABASE [test] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [test] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [test] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [test] SET ALLOW_SNAPSHOT_ISOLATION ON
GO
ALTER DATABASE [test] SET READ_COMMITTED_SNAPSHOT ON
GO
ALTER DATABASE [test] SET READ_WRITE
GO
ALTER DATABASE [test] SET RECOVERY SIMPLE
GO
ALTER DATABASE [test] SET MULTI_USER
GO
ALTER DATABASE [test] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [test] SET TARGET_RECOVERY_TIME = 0 SECONDS
GO
ALTER DATABASE [test] SET DELAYED_DURABILITY = DISABLED
GO
USE [test]
GO
IF NOT EXISTS (SELECT name FROM sys.filegroups WHERE is_default=1 AND name = N'PRIMARY') ALTER DATABASE [test] MODIFY FILEGROUP [PRIMARY] DEFAULT
GO
and then execute this file with powershell... Is that an option for you?

This script demonstrates all the flags for the default database creation T-SQL in SQL 2016:
$DB=[Microsoft.SqlServer.Management.Smo.Database]::new($Server,"TemporaryDB")
# CONTAINMENT = NONE
$DB.ContainmentType=[Microsoft.SqlServer.Management.Smo.ContainmentType]::None
#ALTER DATABASE [TemporaryDB] SET COMPATIBILITY_LEVEL = 130
$DB.CompatibilityLevel=130
#ALTER DATABASE [TemporaryDB] SET ANSI_NULL_DEFAULT OFF
$DB.AnsiNullDefault=$false
#ALTER DATABASE [TemporaryDB] SET ANSI_NULLS OFF
$DB.AnsiNullsEnabled=$false
#ALTER DATABASE [TemporaryDB] SET ANSI_PADDING OFF
$DB.AnsiPaddingEnabled=$false
#ALTER DATABASE [TemporaryDB] SET ANSI_WARNINGS OFF
$DB.AnsiWarningsEnabled=$false
#ALTER DATABASE [TemporaryDB] SET ARITHABORT OFF
$DB.ArithmeticAbortEnabled=$false
#ALTER DATABASE [TemporaryDB] SET AUTO_CLOSE OFF
$DB.AutoClose=$false
#ALTER DATABASE [TemporaryDB] SET AUTO_SHRINK OFF
$DB.AutoShrink=$false
#ALTER DATABASE [TemporaryDB] SET AUTO_CREATE_STATISTICS ON(INCREMENTAL = OFF)
$DB.AutoCreateStatisticsEnabled=$true
$DB.AutoCreateIncrementalStatisticsEnabled=$false
#ALTER DATABASE [TemporaryDB] SET AUTO_UPDATE_STATISTICS ON
$DB.AutoUpdateStatisticsEnabled=$false
#ALTER DATABASE [TemporaryDB] SET CURSOR_CLOSE_ON_COMMIT OFF
$DB.CloseCursorsOnCommitEnabled=$false
#ALTER DATABASE [TemporaryDB] SET CURSOR_DEFAULT GLOBAL
$DB.LocalCursorsDefault=$false
#ALTER DATABASE [TemporaryDB] SET CONCAT_NULL_YIELDS_NULL OFF
$DB.ConcatenateNullYieldsNull=$false
#ALTER DATABASE [TemporaryDB] SET NUMERIC_ROUNDABORT OFF
$DB.NumericRoundAbortEnabled=$false
#ALTER DATABASE [TemporaryDB] SET QUOTED_IDENTIFIER OFF
$DB.QuotedIdentifiersEnabled=$false
#ALTER DATABASE [TemporaryDB] SET RECURSIVE_TRIGGERS OFF
$DB.RecursiveTriggersEnabled=$false
#ALTER DATABASE [TemporaryDB] SET DISABLE_BROKER
$DB.BrokerEnabled=$false
#ALTER DATABASE [TemporaryDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
$DB.AutoUpdateStatisticsAsync=$false
#ALTER DATABASE [TemporaryDB] SET DATE_CORRELATION_OPTIMIZATION OFF
$DB.DateCorrelationOptimization=$false
#ALTER DATABASE [TemporaryDB] SET PARAMETERIZATION SIMPLE
$DB.IsParameterizationForced=$false
#ALTER DATABASE [TemporaryDB] SET READ_COMMITTED_SNAPSHOT OFF
$DB.IsReadCommittedSnapshotOn=$false
#ALTER DATABASE [TemporaryDB] SET READ_WRITE
$DB.ReadOnly=$false
#ALTER DATABASE [TemporaryDB] SET RECOVERY FULL
$DB.RecoveryModel=[Microsoft.SqlServer.Management.Smo.RecoveryModel]::Full
#ALTER DATABASE [TemporaryDB] SET MULTI_USER
$DB.UserAccess=[Microsoft.SqlServer.Management.Smo.DatabaseUserAccess]::Multiple
#ALTER DATABASE [TemporaryDB] SET PAGE_VERIFY CHECKSUM
$DB.PageVerify=[Microsoft.SqlServer.Management.Smo.PageVerify]::Checksum
#ALTER DATABASE [TemporaryDB] SET TARGET_RECOVERY_TIME = 60 SECONDS
$DB.TargetRecoveryTime=60
#ALTER DATABASE [TemporaryDB] SET DELAYED_DURABILITY = DISABLED
$DB.DelayedDurability=[Microsoft.SqlServer.Management.Smo.DelayedDurability]::Disabled
#ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;
$DB.MaxDop=0
#ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;
$DB.MaxDopForSecondary=[Microsoft.SqlServer.Management.Smo.DatabaseScopedConfigurationOnOff]::Primary
#ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;
$DB.LegacyCardinalityEstimation=[Microsoft.SqlServer.Management.Smo.DatabaseScopedConfigurationOnOff]::Off
#ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;
$DB.LegacyCardinalityEstimationForSecondary=[Microsoft.SqlServer.Management.Smo.DatabaseScopedConfigurationOnOff]::Primary
#ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;
$DB.ParameterSniffing=[Microsoft.SqlServer.Management.Smo.DatabaseScopedConfigurationOnOff]::On
#ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = PRIMARY;
$DB.ParameterSniffingForSecondary=[Microsoft.SqlServer.Management.Smo.DatabaseScopedConfigurationOnOff]::Primary
#ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;
$DB.QueryOptimizerHotfixes=[Microsoft.SqlServer.Management.Smo.DatabaseScopedConfigurationOnOff]::Off
#ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = PRIMARY;
$DB.QueryOptimizerHotfixesForSecondary=[Microsoft.SqlServer.Management.Smo.DatabaseScopedConfigurationOnOff]::Primary

Turns out I can just call $Db.SomeFlag = $someValue and that works, for example:
$Db.AutoShrink = $True

Related

SQL Server: The ALTER TABLE statement conflicted with the CHECK constraint

I am confused about why this doesn't work:
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.Accounts ADD CONSTRAINT
CK_client_not_null CHECK (site <> 'LWOP' and client is not null)
GO
ALTER TABLE dbo.Accounts SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
will throw this error:
Msg 547, Level 16, State 0, Line 13
The ALTER TABLE statement conflicted with the CHECK constraint "CK_client_not_null". The conflict occurred in database "ss", table "dbo.Accounts".
Msg 3902, Level 16, State 1, Line 18
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
but when I run the following:
select *
from Accounts
where site = 'LWOP' or client is null
I am getting only that row that can have client as null.
What am I missing here?
Once again: I want to make a constraint that will restrict null values on client column ONLY if site <> 'LWOP', so how to do it?
Thanks,
Dejan
I found the solution already:
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.Accounts ADD CONSTRAINT
CK_client_not_null CHECK (site <> 'LWOP' and client is not null OR site = 'LWOP')
GO
ALTER TABLE dbo.Accounts SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
site <> 'LWOP' and client is not null OR site = 'LWOP' - that covers all situations for check to work.

SQL server set AUTOGROW_ALL_FILES fails

I try to execute this:
USE [MyDB]
GO
declare #autogrow bit
SELECT #autogrow=convert(bit, is_autogrow_all_files) FROM sys.filegroups WHERE name=N'PRIMARY'
if(#autogrow=0)
ALTER DATABASE [MyDB] MODIFY FILEGROUP [PRIMARY] AUTOGROW_ALL_FILES
GO
And it fails with:
Database state cannot be changed while other users are using the database 'HistoryDBTest'
How can I go around it?
You'll need to change the database to single user mode. Use this with care; considering the error is "other users are using the database" this means that those users will have their connections to the database cut off, and their transactions rolled back.
USE master;
GO
ALTER DATABASE MyDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
USE [MyDB];
GO
DECLARE #autogrow bit;
SELECT #autogrow = CONVERT(bit, is_autogrow_all_files)
FROM sys.filegroups
WHERE name = N'PRIMARY';
IF (#autogrow = 0) ALTER DATABASE [MyDB] MODIFY FILEGROUP [PRIMARY] AUTOGROW_ALL_FILES;
GO
USE master;
GO
ALTER DATABASE MyDB SET MULTI_USER;

Switching a user in SQL Server fails when accessing through user's default schema in stored proc

I'm trying to implement shared API in MS SQL Server 2014 DB. In that architecture, schemas should have similar structures and use shared API owned by dbo whereas at the same time exposes own API. To call one another without qualifying object names, EXECUTE AS USER statement is used for context switching to a certain default schema of the current user.
The problem is here: while immediate access with user context switching works fine (e.g. EXECUTE AS USER followed by SELECT * from test_tbl;), the access through default schema in a stored procedure fails with error Msg 208, Level 16, State 1.
Before posting my question, I tried a lot of experiments and tests and searched MSDN, Web and SQL forums for any clue during several days with no luck.
Scripts for reproducing (<MDF> and <LDF> requires substitutions with appropritate file paths):
-- DB creation
CREATE DATABASE [test_sql]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'test_sql', FILENAME = N'<MDF>' , SIZE = 5120KB , FILEGROWTH = 1024KB )
LOG ON
( NAME = N'test_sql_log', FILENAME = N'<LDF>' , SIZE = 2048KB , FILEGROWTH = 10%)
COLLATE Cyrillic_General_CI_AS
GO
ALTER DATABASE [test_sql] SET COMPATIBILITY_LEVEL = 120
GO
ALTER DATABASE [test_sql] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [test_sql] SET ANSI_NULLS OFF
GO
ALTER DATABASE [test_sql] SET ANSI_PADDING OFF
GO
ALTER DATABASE [test_sql] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [test_sql] SET ARITHABORT OFF
GO
ALTER DATABASE [test_sql] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [test_sql] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [test_sql] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [test_sql] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [test_sql] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [test_sql] SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [test_sql] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [test_sql] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [test_sql] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [test_sql] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [test_sql] SET DISABLE_BROKER
GO
ALTER DATABASE [test_sql] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [test_sql] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [test_sql] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [test_sql] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [test_sql] SET READ_WRITE
GO
ALTER DATABASE [test_sql] SET RECOVERY FULL
GO
ALTER DATABASE [test_sql] SET MULTI_USER
GO
ALTER DATABASE [test_sql] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [test_sql] SET TARGET_RECOVERY_TIME = 0 SECONDS
GO
ALTER DATABASE [test_sql] SET DELAYED_DURABILITY = DISABLED
GO
USE [test_sql]
GO
IF NOT EXISTS (SELECT name FROM sys.filegroups WHERE is_default=1 AND name = N'PRIMARY') ALTER DATABASE [test_sql] MODIFY FILEGROUP [PRIMARY] DEFAULT
GO
-- Srv login, DB user and schema creation
CREATE LOGIN [test_usr_login] WITH PASSWORD=N'test_usr_login', DEFAULT_DATABASE=[test_sql], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
CREATE USER [test_usr] FOR LOGIN [test_usr_login] WITH DEFAULT_SCHEMA=[test_schema]
GO
CREATE SCHEMA [test_schema] AUTHORIZATION [test_usr]
GO
-- Table and stored proc creation
IF OBJECT_id("[test_schema].[test_tbl]", "U") IS NOT NULL
DROP TABLE [test_schema].[test_tbl];
GO
CREATE TABLE [test_schema].[test_tbl](
[tc] [nchar](10) NULL
) ON [PRIMARY]
GO
IF OBJECT_id("[dbo].[TA]", "P") IS NOT NULL
DROP PROCEDURE [dbo].[TA];
GO
CREATE PROCEDURE [dbo].[TA] AS BEGIN
SET NOCOUNT ON;
SELECT * FROM
(VALUES
('CURRENT_USER', CURRENT_USER),
('SCHEMA_NAME', SCHEMA_NAME()),
('have_UNqualified_select', cast(HAS_PERMS_BY_NAME("[test_tbl]", "OBJECT", "SELECT") as nchar(10))),
('have_qualified_select', cast(HAS_PERMS_BY_NAME("[test_schema].[test_tbl]", "OBJECT", "SELECT") as nchar(10)))
) AS tmptbl([key], val); -- select permissions fro [test_tbl] of the current user
SELECT tc as qualified_tc FROM [test_schema].[test_tbl]; -- qualified select
SELECT tc as UNqualified_tc from [test_tbl]; -- unqualified select fails with Msg 208
END
GO
GRANT EXECUTE ON [dbo].[TA] TO [test_usr]
GO
Test script:
USE [test_sql]
GO
DECLARE #return_value int
execute as login = N'test_usr_login'; -- even when logged in with test_usr_logn, Msg 208 occurs
EXEC #return_value = [dbo].[TA]
revert
SELECT 'Return Value' = #return_value
GO
Output message:
Msg 208, Level 16, State 1, Procedure TA, Line 14 Invalid object name
'test_tbl'.
(1 row(s) affected)
Output result:
key val
CURRENT_USER test_usr
SCHEMA_NAME test_schema
have_UNqualified_select 1
have_qualified_select 1
I would appreciate anyone who could bring light to the solution to the problem described.
The problem is here: while immediate access with user context
switching works fine (e.g. EXECUTE AS USER followed by SELECT * from
test_tbl;), the access through default schema in a stored procedure
fails with error Msg 208, Level 16, State 1.
The problem here is that you don't know how SQL Server resolves non qualified object name.
When you execute plain sql and use an object without specifying its schema, first user default schema is checked, if object is not found, dbo schema is checked. If the object is not found even in dbo, the error is raised.
It's different when it comes to stored procedure. If schema is not specified, sp's schema is checked first, if object is not found, dbo schema is checked, if it's not found again the error is raised. User default schema is never checked in case of stored procedure

Invalid object name 'Import_Table'. in SQL Server

After creating my database using the script shown below, if I execute 'select * from import_table' it gives error saying "Invalid object name 'Import_Table'" . I know it will run perfectly if I change the query to 'select * from hrobuser.import_table' , which is not possible from our end to suffix the the user name(hrobuser) in the query.
So can anyone tell me that is this the only way to execute or is there any other solution for this particular issue.
Thanks in advance.
USE master
GO
SET DATEFORMAT MDY
CREATE DATABASE HROB3_0
IF NOT EXISTS( SELECT name FROM SYS.DATABASES WHERE name = 'HROB3_0' )
BEGIN
RAISERROR( N'Database was not successfully created. Review the script for incorrect parameters.', 20, -1) WITH LOG;
END;
GO
--###################################
-- Alter Database and set the options
--###################################
ALTER DATABASE HROB3_0 SET RECOVERY FULL
GO
--Automatic Options
ALTER DATABASE HROB3_0 SET AUTO_CLOSE OFF
GO
ALTER DATABASE HROB3_0 SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE HROB3_0 SET AUTO_SHRINK OFF
GO
ALTER DATABASE HROB3_0 SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE HROB3_0 SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
-- Cursor Options
ALTER DATABASE HROB3_0 SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE HROB3_0 SET CURSOR_DEFAULT GLOBAL
GO
-- Miscellaneous Options
ALTER DATABASE HROB3_0 SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE HROB3_0 SET ANSI_NULLS OFF
GO
ALTER DATABASE HROB3_0 SET ANSI_PADDING OFF
GO
ALTER DATABASE HROB3_0 SET ANSI_WARNINGS OFF
GO
ALTER DATABASE HROB3_0 SET ARITHABORT OFF
GO
ALTER DATABASE HROB3_0 SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE HROB3_0 SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE HROB3_0 SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE HROB3_0 SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE HROB3_0 SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE HROB3_0 SET TRUSTWORTHY OFF
GO
ALTER DATABASE HROB3_0 SET PARAMETERIZATION SIMPLE
GO
--Recovery Options
ALTER DATABASE HROB3_0 SET PAGE_VERIFY CHECKSUM
GO
--State Options
ALTER DATABASE HROB3_0 SET READ_WRITE
GO
ALTER DATABASE HROB3_0 SET MULTI_USER
GO
--########################################
-- Create login user and schema
--########################################
USE HROB3_0
GO
CREATE LOGIN hrobuser WITH PASSWORD = 'imagenow', DEFAULT_DATABASE = HROB3_0, DEFAULT_LANGUAGE=us_english, CHECK_EXPIRATION=OFF, CHECK_POLICY = OFF
GO
CREATE USER hrobuser FOR LOGIN hrobuser WITH DEFAULT_SCHEMA=hrobuser
GO
CREATE SCHEMA hrobuser AUTHORIZATION hrobuser
GO
EXEC sp_addrolemember 'db_owner', 'hrobuser'
GO
USE MASTER
GO
GRANT VIEW SERVER STATE TO hrobuser
GO
USE HROB3_0
GO
EXECUTE AS user = 'hrobuser'
GO
CREATE TABLE IMPORT_TABLE
(
ID int IDENTITY(1,1) PRIMARY KEY,
EMPLOYEE_ID VARCHAR(10) not null,
EMPLOYEE_NAME_FIRST VARCHAR(20),
EMPLOYEE_NAME_LAST VARCHAR(20),
SUPERVISOR_NAME_FULL VARCHAR(40),
SUPERVISOR_EMAIL_WORK VARCHAR(70),
EMPLOYEE_HOMEADDRESS_STREET VARCHAR(20),
EMPLOYEE_HOMEADDRESS_APT VARCHAR(20),
EMPLOYEE_HOMEADDRESS_CITY VARCHAR(20),
EMPLOYEE_HOMEADDRESS_STATE VARCHAR(30),
EMPLOYEE_HOMEADDRESS_ZIP int,
EMPLOYEE_PHONE_HOME int,
EMPLOYEE_EMAIL_PERSONAL VARCHAR(70),
EMPLOYEE_TITLE VARCHAR(20),
LOCATION_REFERENCE_1 VARCHAR(20),
LOCATION_REFERENCE_2 VARCHAR(20),
REFERENCE_1 VARCHAR(30),
REFERENCE_2 VARCHAR(30),
WORK_STATE VARCHAR(20),
DATE_HIRED DATE,
ADDITIONAL_EMP_INFO_1 VARCHAR(150),
ADDITIONAL_EMP_INFO_2 VARCHAR(150),
ADDITIONAL_EMP_INFO_3 VARCHAR(150),
ADDITIONAL_EMP_INFO_4 VARCHAR(150),
ADDITIONAL_EMP_INFO_5 VARCHAR(150),
UNIQUE (EMPLOYEE_ID)
);
GO
Does your user has permission to create table in your database. If not then provide the same.
Check the below code and hope this will help.
USE mydatabase
GRANT ALTER ON Schema :: DBO TO user_mydatabase
GRANT CREATE TABLE TO user_mydatabase
GO
and then you can add your code to execute as user "EXECUTE AS user = 'hrobuser' ......"

Database script not executing in SQL Server 2008

In my SQL Server 2008 R2, I have a database script which generates successfully, but when I am trying to execute that script it only shows Executing query message and nothing happen.
I had waited at-least 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 don't know what's going on...
More details: This thing is not happening on particular DataBase, it is a problem on all the database of my SQL Server.
lets see it by example.
In SQL Server 2008 R2, I have following type of script.
USE [master]
GO
/****** Object: Database [BillingApplication] Script Date: 01/22/2013 17:42:04 ******/
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'BillingApplication')
BEGIN
CREATE DATABASE [BillingApplication] ON PRIMARY
( NAME = N'BillingApplication', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\BillingApplication.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'BillingApplication_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\BillingApplication_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
END
GO
ALTER DATABASE [BillingApplication] SET COMPATIBILITY_LEVEL = 100
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [BillingApplication].[dbo].[sp_fulltext_database] #action = 'enable'
end
GO
ALTER DATABASE [BillingApplication] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [BillingApplication] SET ANSI_NULLS OFF
GO
ALTER DATABASE [BillingApplication] SET ANSI_PADDING OFF
GO
ALTER DATABASE [BillingApplication] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [BillingApplication] SET ARITHABORT OFF
GO
ALTER DATABASE [BillingApplication] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [BillingApplication] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [BillingApplication] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [BillingApplication] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [BillingApplication] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [BillingApplication] SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [BillingApplication] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [BillingApplication] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [BillingApplication] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [BillingApplication] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [BillingApplication] SET DISABLE_BROKER
GO
ALTER DATABASE [BillingApplication] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [BillingApplication] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [BillingApplication] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [BillingApplication] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [BillingApplication] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [BillingApplication] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [BillingApplication] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [BillingApplication] SET READ_WRITE
GO
ALTER DATABASE [BillingApplication] SET RECOVERY FULL
GO
ALTER DATABASE [BillingApplication] SET MULTI_USER
GO
ALTER DATABASE [BillingApplication] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [BillingApplication] SET DB_CHAINING OFF
GO
EXEC sys.sp_db_vardecimal_storage_format N'BillingApplication', N'ON'
GO
USE [BillingApplication]
GO
/****** Object: Table [dbo].[tbCustBill] Script Date: 01/22/2013 17:42:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbCustBill]') AND type in (N'U'))
BEGIN
-- And continue the entire script
Now as I had seen in SQL Server Profiler than the execution till following code work perfectly.
ALTER DATABASE [BillingApplication] SET RECURSIVE_TRIGGERS OFF
GO
And on the the next line executing become stop.
I don't know what's going on....
On force full stop of execution its generate error as below
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.
So, that's it may be some SQL Sever configuration problem...
I think you need to ensure you can place an exclusive lock on the database to change this setting. Even though you just created the database you may have established more than one connection to it. Make sure you disable IntelliSense in Management Studio, that you have no other windows connected to this database, and that you switch context to another database. Then set the database to single user, make your changes, and set it back:
USE master;
GO
ALTER DATABASE BillingApplication SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
ALTER DATABASE BillingApplication SET RECURSIVE_TRIGGERS OFF;
GO
ALTER DATABASE BillingApplication SET DISABLE_BROKER;
GO
... other changes ...
ALTER DATABASE BillingApplication SET MULTI_USER;
GO
If this still waits then you may be waiting on some very large transaction to roll back, and you can check in another window what you are waiting for by looking at sys.dm_exec_requests and/or sys.dm_os_waiting_tasks.
Though, if you are creating the database, why do you think you need to explicitly disable broker? It's not enabled by default...
You have
ALTER DATABASE [BillingApplication] SET DISABLE_BROKER
without ane ON or OFF. Set that and it should work.
Nope, that's not it. I'd guess it has something to do with the Service Broker sub-system, but that's not something I'm familiar with. Hopefully someone else who knows that system can answer this...\

Resources