Showing posts with label and. Show all posts
Showing posts with label and. Show all posts

Wednesday, August 22, 2018

List out all MDF and LDF File locations of SQL Sever Databases

SELECT
    db.name AS DBName,
    type_desc AS FileType,
    Physical_Name AS Location
FROM
    sys.master_files mf
INNER JOIN
    sys.databases db ON db.database_id = mf.database_id

Wednesday, January 25, 2017

Difference between Detaching database and bringing database Offline

SQL Server Offline and Detach Database




Detach Database/Attach Database: The data and transaction log files of a database can be detached and then reattached to the same or another instance of SQL Server. Detaching and attaching a database is useful if you want to change the database to a different instance of SQL Server on the same computer or to move the database.
Detaching a database removes it from the instance of SQL Server but leaves the database intact within its data files and transaction log files. These files can then be used to attach the database to any instance of SQL Server, including the server from which the database was detached.

you can attach a copied or detached SQL Server database. When you attach a SQL Server 2005 database that contains full-text catalog files onto a SQL Server 2016 server instance, the catalog files are attached from their previous location along with the other database files, the same as in SQL Server When you attach a database, all data files (MDF and NDF files) must be available. If any data file has a different path from when the database was first created or last attached, you must specify the current path of the file.

The requirement for attaching log files depends partly on whether the database is read-write or read-only, as follows:
  • For a read-write database, you can usually attach a log file in a new location. However, in some cases, reattaching a database requires its existing log files. Therefore, it is important to always keep all the detached log files until the database has been successfully attached without them.
    If a read-write database has a single log file and you do not specify a new location for the log file, the attach operation looks in the old location for the file. If it is found, the old log file is used, regardless of whether the database was shut down cleanly. However, if the old log file is not found and if the database was shut down cleanly and has no active log chain, the attach operation attempts to build a new log file for the database.
  • If the primary data file being attached is read-only, the Database Engine assumes that the database is read-only. For a read-only database, the log file or files must be available at the location specified in the primary file of the database. A new log file cannot be built because SQL Server cannot update the log location stored in the primary file.
Database Offline: Database is unavailable. A database becomes offline by explicit user action and remains offline until additional user action is taken. For example, the database may be taken offline in order to move a file to a new disk. The database is then brought back online after the move has been completed.


Use OFFLINE and ONLINE
1) If you are trying to make the database temporary unavailable for a period of time, you could take the database OFFLINE, and make it available by bringing it ONLINE whenever it is or you are ready.

2a) If you want to move the database or log files to different physical location or changing the database and/or log physical file name, AND keep them within the same SQL Server instance.
- Before you take the database offline, you need to know the logical name of the file. The name field is the logical name for the physical file name that you are about to change the path. Record the logical name for later use.

SELECT name, type, type_desc, physical_name, state, state_desc
FROM sys.master_files
WHERE database_id = DB_ID('YourDatabase')

- Take the database OFFLINE.
ALTER DATABASE YourDatabase SET OFFLINE
WITH ROLLBACK IMMEDIATE;

-Move the database and/or log files to different location.
- Update the database and/or log files path registered on its SQL Server instance. Execute the T-SQL command for each database and log files,

ALTER DATABASE YourDatabase 
MODIFY FILE (NAME = YourFileLogicalName,
FILENAME = 'Your Database or Log new physical path')

Bring the database ONLINE.
ALTER DATABASE YourDatabase SET ONLINE;

If you just want to change the logical name, you dont have to take the database OFFLINE. You could change it on SSMS or T-SQL.

Right click on the database > Properties > Select Page > Change it under Logical Name column > OK.

ALTER DATABASE YourDatabase 
MODIFY FILE (NAME = YourFileLogicalName,
NEWNAME = YourFileNewLogicalName)

2b) If you are relocating a file during part of the scheduled disk maintenance process, you may need to change the file path registered on its SQL Server instance before taking the database OFFLINE. This assure the server has the right path for the database and log files when the instance restart, after being shut down for maintenance.
- When the database and/or log file path is successfully updated on the instance, a message will show; 'The file "YourDatabaseFile" has been modified in the system catalog. The new path will be used the next time the database is started.'

Use DETACH and ATTACH,
1) If you want to move the database and log files to a different SQL Server instance or another server.
- Rollback active transaction and gain exclusive access. Detach the database. (optional: update statistics) 

ALTER DATABASE YourDatabase SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;

EXEC sp_detach_db 'YourDatabase', 'true'

- Move database and log files to different location.
- Attach the database on different instance on same/another server. 

USE master;

CREATE DATABASE YourDatabase
ON (FILENAME = 'the physical path of your database file')
LOG ON (FILENAME = 'the physical path of your log file')
FOR ATTACH;

- If the database has previously set to single user, you may want to set it to multiple user access option.

ALTER DATABASE YourDatabase SET MULTI_USER

2) Even though you can choose to detach and attach the database back on the same SQL Server instance for scenario like changing physical path or file name, it is recommended to use the OFFLINE and ONLINE methods due to the restriction and limitation on DETACH. When you detach a database, you remove the database from the instance. It is required to remove the database from any participation of replication, mirroring and snapshot.

Reference: 







Tuesday, October 25, 2016

How to Stop SQL Server Agent Job while it is actively running?

How to Stop SQL Server Agent Job while it is actively running?

Try running sp_who2 and find the SPID and kill the process using KILL SPID with status only so that it will show the rollbackup completed as well.



Difference between KILL and KILL WITH STATUSONLY – Estimate Rollback completion time




While I was talking to a customer during a replication scenario, customer asked me a question about understanding the estimated completion time for a rollback.

I was explaining that we have KILL WITH STATUSONLY but it will just report the progress only if the SPID was killed already and it will not kill the SPID also KILL WITH STATUSONLY will not help to track the progress of ROLLBACK issued by ROLLBACK TRAN. This was something new to him that KILL WITH STATUSONLY will not kill the SPID instead it only reports the progress. 

I thought of sharing this in a blog so that it will be useful for others who overlooked the KILL command.

Here is what BOL says:

KILL WITH STATUSONLY does not terminate or roll back the session ID or UOW; the command only displays the current progress of the rollback.

Lab:
Step 1: I ran a long running batch from SPID 52 

Step 2: Issued a KILL using the command KILL 52

Step 3: Here is what I observed from SP_WHO2 52:
SPID
Status
Login
HostName
BlkBy
DBName
Command
52
SUSPENDED                    
abc
def
.
microsoft
KILLED/ROLLBACK

Step 4: Here is what I got when I ran KILL 52 WITH STATUSONLY:
spid 52: Transaction rollback in progress. Estimated rollback completion: 80% Estimated time left: 10 seconds.

Step 5: I tried to run the same statement from a different SPID 53 inside an explicit transaction and issued a ROLLBACK TRAN and this is the status when I ranSP_WHO2 53:
SPID
Status
Login
HostName
BlkBy
DBName
Command
53
ROLLBACK                      
abc
def
.
microsoft
ROLLBACK TRANSAC

Step 6: Here is the output of KILL 53 WITH STATUSONLY :
Msg 6120, Level 16, State 1, Line 1
Status report cannot be obtained. Rollback operation for Process ID 53 is not in progress.

So KILL WITH STATUS ONLY cannot be used to track the progress of  ROLLBACK issued by ROLLBACK TRAN. Hope this helps!


Friday, April 17, 2015

SQL Server SSRS: List out all Data Sources and all their dependency objects/Reports

 This Script will list all the data sources by their actual name, and all their dependent items:

SELECT C2.NAME AS Data_Source_Name
 ,C.NAME AS Dependent_Item_Name
 ,C.Path AS Dependent_Item_Path
FROM ReportServer.dbo.DataSource AS DS
INNER JOIN ReportServer.dbo.CATALOG AS C ON DS.ItemID = C.ItemID
 AND DS.Link IN (
  SELECT ItemID
  FROM ReportServer.dbo.CATALOG
  WHERE Type = 5
  ) --Type 5 identifies data sources
FULL JOIN ReportServer.dbo.CATALOG C2 ON DS.Link = C2.ItemID
WHERE C2.Type = 5
ORDER BY C2.NAME ASC
 ,C.NAME ASC;

Monday, October 27, 2014

Wednesday, October 8, 2014

List of Permissions and their Description in SQL Server

Permission name  Description
ALTER  Permission to modify the object's definition

CONNECT 
Permission to access the database or connect to the endpoint

DELETE 
Permission to delete the object

EXECUTE
 Permission to execute the stored procedure or the function

IMPERSONATE
 Permission to take the identity of a principal, by the means of an EXECUTE AS command

INSERT 
Permission to insert data into the table or view

REFERENCES 
Permission to reference the object in a foreign key definition, or to declare a view or function WITH SCHEMABINDING referencing the object

SELECT
 Permission to issue a SELECT command against the object or column

TAKE OWNERSHIP
 Permission to become the owner of the object

UPDATE
 Permission to update the data

VIEW DEFINITION 
Permission to view the definition (structure) of the object

Preventing logins and users to see metadata in SQL Server

To hide databases to all LOGINS, remove/revoke "VIEW ANY DATABASE" permission from the public server role


USE master;
GO

REVOKE VIEW ANY DATABASE
 TO PUBLIC;



To allow only some logins to view all databases, Jus create a user-defined server role


USE master;

CREATE SERVER ROLE [DBViewer];
GO

GRANT VIEW ANY DATABASE
 TO [DBViewer];

ALTER SERVER ROLE [DBViewer] ADD MEMBER [MyLogin];

This code creates a server role named DBViewer and grants the
VIEW ANY DATABASE permission to it. It then adds the login MyLogin to it.

Note: MASTER and TEMPDB will always be visible to all logins,We cannot make them invisible.

Thursday, September 25, 2014

The MSSQLServer service terminated unexpectedly. Check the SQL Server error log and Windows System and Application event logs for possible causes.




Solution: 


Oops! You might be running a very old build of SQL Server. Immediately check for new release of Service Packs, I would recommend installing recent service pack and then the latest cumulative update package.


If the Service pack installation didn't solve your Issue

For additional help, Open a case with Microsoft immediately.

Tuesday, September 23, 2014

Script to sync up logins and database users in SQL Server

USE DATABASE
GO

EXEC sp_change_users_login 'update_one'
 ,'databse username'
 ,'loginname'
GO

Script to find date and details when database was restored in SQL Server

USE msdb;

SELECT DBRestored = destination_database_name
 ,RestoreDate = restore_date
 ,SourceDB = b.database_name
 ,SourceFile = physical_name
 ,BackupDate = backup_start_date
FROM RestoreHistory h
INNER JOIN BackupSet b ON h.backup_set_id = b.backup_set_id
INNER JOIN BackupFile f ON f.backup_set_id = b.backup_set_id
ORDER BY RestoreDate

Script to drop all Foreign keys and recreate them

--Create Table and Save Foreign Keys in a Table

--Drop and Recreate Foreign Key Constraints SET NOCOUNT ON DECLARE @counter INT DECLARE @constraint NVARCHAR(200) DECLARE @schema NVARCHAR(200) DECLARE @table NVARCHAR(200) CREATE TABLE fklist ( RowId INT PRIMARY KEY IDENTITY(1, 1) ,ForeignKeyConstraintName NVARCHAR(200) ,ForeignKeyConstraintTableSchema NVARCHAR(200) ,ForeignKeyConstraintTableName NVARCHAR(200) ,ForeignKeyConstraintColumnName NVARCHAR(200) ,PrimaryKeyConstraintName NVARCHAR(200) ,PrimaryKeyConstraintTableSchema NVARCHAR(200) ,PrimaryKeyConstraintTableName NVARCHAR(200) ,PrimaryKeyConstraintColumnName NVARCHAR(200) ) INSERT INTO fklist ( ForeignKeyConstraintName ,ForeignKeyConstraintTableSchema ,ForeignKeyConstraintTableName ,ForeignKeyConstraintColumnName ) SELECT U.CONSTRAINT_NAME ,U.TABLE_SCHEMA ,U.TABLE_NAME ,U.COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE U INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME WHERE C.CONSTRAINT_TYPE = 'FOREIGN KEY' UPDATE fklist SET PrimaryKeyConstraintName = UNIQUE_CONSTRAINT_NAME FROM fklist T INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R ON T.ForeignKeyConstraintName = R.CONSTRAINT_NAME UPDATE fklist SET PrimaryKeyConstraintTableSchema = TABLE_SCHEMA ,PrimaryKeyConstraintTableName = TABLE_NAME FROM fklist T INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C ON T.PrimaryKeyConstraintName = C.CONSTRAINT_NAME UPDATE fklist SET PrimaryKeyConstraintColumnName = COLUMN_NAME FROM fklist T INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U ON T.PrimaryKeyConstraintName = U.CONSTRAINT_NAME SELECT * FROM fklist




--DROP CONSTRAINT:
--set counter variable to number of rows inserted
SELECT @counter = MAX(RowId)
FROM fklist

--exec alter table to drop each constriant
WHILE @counter > 0
BEGIN
 SELECT @constraint = ForeignKeyConstraintName
  ,@schema = ForeignKeyConstraintTableSchema
  ,@table = ForeignKeyConstraintTableName
 FROM fklist
 WHERE RowId = @counter

 --exec ('alter table [' + @schema + '].[' + @table + '] drop constraint [' + @constraint + ']')
 PRINT ('alter table [' + @schema + '].[' + @table + '] drop constraint [' + @constraint + ']')

 SET @counter = @counter - 1
END

-----------------------------------------------------------------------------------

--Drop Foreign Keys

SET NOCOUNT ON DECLARE @counter INT DECLARE @constraint NVARCHAR(200) DECLARE @schema NVARCHAR(200) DECLARE @table NVARCHAR(200) --DROP CONSTRAINT: --set counter variable to number of rows inserted SELECT @counter = MAX(RowId) FROM fklist --exec alter table to drop each constriant WHILE @counter > 0 BEGIN SELECT @constraint = ForeignKeyConstraintName ,@schema = ForeignKeyConstraintTableSchema ,@table = ForeignKeyConstraintTableName FROM fklist WHERE RowId = @counter --exec ('alter table [' + @schema + '].[' + @table + '] drop constraint [' + @constraint + ']') PRINT ('alter table [' + @schema + '].[' + @table + '] drop constraint [' + @constraint + ']') SET @counter = @counter - 1 END

--Recreate Foreign Keys

SET NOCOUNT ON DECLARE @counter INT DECLARE @constraint NVARCHAR(200) DECLARE @constraint_col NVARCHAR(200) DECLARE @schema NVARCHAR(200) DECLARE @pk_schema NVARCHAR(200) DECLARE @table NVARCHAR(200) DECLARE @pk_table NVARCHAR(200) DECLARE @pk_col NVARCHAR(200) --DROP CONSTRAINT: --set counter variable to number of rows inserted SELECT @counter = MAX(RowId) FROM fklist --exec alter table to drop each constriant WHILE @counter > 0 BEGIN SELECT @constraint = ForeignKeyConstraintName ,@schema = ForeignKeyConstraintTableSchema ,@table = ForeignKeyConstraintTableName ,@constraint_col = ForeignKeyConstraintColumnName ,@pk_schema = PrimaryKeyConstraintTableSchema ,@pk_table = PrimaryKeyConstraintTableName ,@pk_col = PrimaryKeyConstraintColumnName FROM fklist WHERE RowId = @counter PRINT ('ALTER TABLE [' + @schema + '].[' + @table + '] ADD CONSTRAINT ' + @constraint + ' FOREIGN KEY(' + @constraint_col + ') REFERENCES [' + @pk_schema + '].[' + @pk_table + '](' + @pk_col + ')') SET @counter = @counter - 1 END