SQL server set AUTOGROW_ALL_FILES fails - sql-server

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;

Related

Clone a database with sample data in table

I want a script that will quickly delete a Test instance of a database and recreate it with only a sample of rows in each table. I know there is no referential integrity issues or other object restraints such as stored procedures linked to records. I have tried the following but it states database in use. I think I am missing something in between the drop and clone. What am I doing wrong here? Or does this have to be split between two scripts?
-- ensure "master" is selected in SSMS
IF EXISTS(select * from sys.databases where name='shoesales_TEST')
ALTER DATABASE shoesales_TEST set single_user with rollback immediate
GO
IF EXISTS(select * from sys.databases where name='shoesales_TEST')
DROP DATABASE shoesales_TEST
GO
DBCC CLONEDATABASE
(
shoesales
, shoesales_TEST
)
GO
ALTER DATABASE shoesales_TEST SET READ_WRITE
GO
USE shoesales_TEST
GO
INSERT INTO shoesales_TEST.dbo.sizesales
SELECT TOP 30 * FROM shoesales.dbo.sizesales
GO

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

How to complete remove filestream and all attached files

I have tried the FILESTREAM feature for MSSQL (2008R2 Data Center) on a local database, to experiment. The real database is running on a server. I have setup the whole FILESTREAM, using this query:
/* CREATE FILESTREAM AND FILESTREAM TABLE */
USE [master]
GO
ALTER DATABASE SenONew
ADD FILEGROUP [FileStream]
CONTAINS FILESTREAM
GO
ALTER DATABASE SenONew
ADD FILE
(
NAME = 'fsSenONew',
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\SenONew.ndf'
)
TO FILEGROUP [FileStream]
GO
USE [SenONew]
GO
CREATE TABLE Filestore(
FileID int PRIMARY KEY,
RowID uniqueidentifier ROWGUIDCOL NOT NULL UNIQUE DEFAULT NEWSEQUENTIALID(),
FileDescr nvarchar(max),
FileIndex varbinary(max) FILESTREAM NULL)
GO
And I was experimenting with adding a few files then deleting them.
Now since this was only meant to be an experiment, I also want to get rid of it. I'm using my local server for the development of the database that will be used on the real server, thus I'm creating BackUp's on my local server then Restore this on the real server, so it gets updated (software is in development, so the database structure changes much as well as the data and I need to do a full restore to the real server, where the software is being tested on).
After hours of searching, I couldn't find anything on my problem.
I understand that I need to:
Remove the database table storing the FILESTREAM information
I need to remove the FILE of the FILESTREAM
Remove the filegroup
So I'm using this query to get rid of everything I set up in the first place:
/* DROP FILESTREAM TABLE AND FILEGROUP */
USE SenONew
DROP TABLE Filestore
GO
ALTER DATABASE SenONew
REMOVE FILE fsSenONew
ALTER DATABASE SenONew
REMOVE FILEGROUP [FileStream]
GO
So I do everything as I should and it completes without error as well. So when I enter my filegroups, files and my file location, I see they are all completely removed:
But when I do a BACKUP of my local database (which include the deleted FILESTREAM, file path and filegroup) and try to restore the server with it, I get errors.
SQL to create a BACKUP:
/* CREATE BACKUP OF DATABASE WITHIN CURRECT CONNECTION */
DECLARE #FileName2 nvarchar(250)
SELECT #FileName2 = (SELECT 'C:\SenO BackUp\' + convert(nvarchar(200),GetDate(),112) + ' SenONew.BAK')
BACKUP DATABASE SenONew TO DISK=#FileName2
GO
Then do the Restore on the server:
/* CREATE RESTORE OF DATABASE WITHIN REAL SERVER CONNECTION */
use master
alter database SenONew set offline with rollback immediate;
DECLARE #FileName2 nvarchar(250)
SELECT #FileName2 = (SELECT '' + convert(nvarchar(200),GetDate(),112) + ' SenONew.BAK')
RESTORE DATABASE SenONew
FROM DISK = #FileName2
alter database SenONew set online with rollback immediate;
I get the following error:
*(Msg 5121, Level 16, State 2, Line 7
The path specified by "C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\SenONew.ndf" is not in a valid directory.
Msg 3156, Level 16, State 3, Line 7 File 'fsSenONew' cannot be restored to 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\SenONew.ndf'. Use WITH MOVE to identify a valid location for the file.
Msg 3119, Level 16, State 1, Line 7 Problems were identified while planning for the RESTORE statement. Previous messages provide details.
Msg 3013, Level 16, State 1, Line 7 RESTORE DATABASE is terminating abnormally. )*
I deleted the .ndf FILESTREAM location, why is it a specified path? Also, why is fsSenONew trying to restore? I can't get my head around it. Are there paths internally that I need to delete?
You can check:
SELECT * FROM SenONew.sys.data_spaces WHERE name = 'FileStream'
it should return 0 rows.
There is a procedure to remove FILESTREAM features from a SQL Server 2008 database :
ALTER TABLE Filestore DROP column FileIndex
GO
ALTER TABLE Filestore SET (FILESTREAM_ON="NULL")
GO
ALTER Database SenONew REMOVE FILE fsSenONew
GO
ALTER Database SenONew REMOVE FILEGROUP [FileStream]
GO
as described in this article. But the steps you did should do the same thing.
Your problem is certainly strange, but I suggest that you try using following
USE SenONew
EXEC Sp_help
EXEC Sp_helpfile
EXEC Sp_helpfilegroup
You may find something suspicious there like another table using that FILEGROUP.
I have done exactly the steps you describe and cannot reproduce your problem. Check how your Restore database screen looks like.
1.Remove the FILESTREAM attribute from columns and tables. You'll need to move data to a new column.
ALTER TABLE MyTable
ADD FileData varbinary(max) NULL;
GO
update MyTable
set FileData = FileStreamData
GO
ALTER TABLE MyTable
DROP column FileStreamData
GO
ALTER TABLE MyTable SET (FILESTREAM_ON="NULL")
GO
EXEC sp_RENAME 'MyTable.FileData', 'FileStreamData', 'COLUMN'
GO
2.Remove files from the FILESTREAM and drop the FILE and FILESTEAM.
ALTER DATABASE [MyDatabase] SET RECOVERY Simple
GO
EXEC SP_FILESTREAM_FORCE_GARBAGE_COLLECTION
ALTER DATABASE [MyDatabase] REMOVE FILE [MyFile]
GO
ALTER DATABASE [MyDatabase] REMOVE FILEGROUP [MyFileGroup]
GO
ALTER DATABASE [MyDatabase] SET RECOVERY FULL
GO
This is my script that worked for me. It was a command missing, to empty the file:
ALTER TABLE FilesTable DROP column FileContent
GO
ALTER TABLE FilesTable SET (FILESTREAM_ON="NULL")
GO
USE mydbname
GO
DBCC SHRINKFILE (N'filestreamfile', EMPTYFILE)
GO
EXEC sp_filestream_force_garbage_collection #dbname = N'mydbname'
ALTER Database mydbname REMOVE FILE filestreamfile
GO
ALTER Database mydbname REMOVE FILEGROUP FILESTREAMGROUP
GO
IF COL_LENGTH('FilesTable','FileContent') IS NULL
BEGIN
ALTER TABLE FilesTable ADD FileContent [varbinary](max) NULL
END
GO

What are the user permissions needed to enable snapshot isolation in a DB?

I have a user who has db_datareader, db_datawriter permissions on a DB.
I want to set the isolation levels to the DB to which the user has access to.
What permissions will my user need to be able to set these.
DB used: SQL SERVER 2008
This is not setting an isolation level:
ALTER DATABASE dbname SET ALLOW_SNAPSHOT_ISOLATION ON;
That is altering the database. For that you need to provide them with ALTER rights on the database:
GRANT ALTER ON DATABASE::dbname TO username;
Otherwise you get this error:
Msg 5011, Level 14, State 9, Line 1
User does not have permission to alter database 'dbname', the database does not exist, or the database is not in a state that allows access checks.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.
Now, ALTER is all or nothing - you can't use it to allow them to change the allow snapshot setting but not other settings like forced parameterization, compatibility level, etc. You can do this much more granularly, though; perhaps you could create a stored procedure that does something like this:
CREATE PROCEDURE dbo.SetIsolationLevel
WITH EXECUTE AS OWNER
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX) = N'ALTER DATABASE '
+ QUOTENAME(DB_NAME())
+ ' SET ALLOW_SNAPSHOT_ISOLATION ON;';
EXEC sp_executesql #sql;
END
GO
Now you just have to give the user EXEC permissions on that procedure, which your user can now call (instead of the ALTER DATABASE command explicitly and instead of giving them full ALTER DATABASE privileges):
GRANT EXEC ON dbo.SetIsolationLevel TO username;
GO
You can simulate them calling this stored procedure by logging in as them, or using the EXECUTE AS feature directly:
EXECUTE AS USER = 'username';
GO
EXEC dbo.SetIsolationLevel;
GO
REVERT;
GO
Another idea is to simply set the model database to have this setting, than any new databases that get created for your users will automatically inherit it, then you don't have to worry about making them turn it on.
ALTER DATABASE model SET ALLOW_SNAPSHOT_ISOLATION ON;
GO
CREATE DATABASE splunge;
GO
SELECT snapshot_isolation_state_desc FROM sys.databases WHERE name = N'splunge';
Result:
ON

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