Sunday, 31 May 2015

SA PASSWORD reset if you do not have any credential


When you are using MS SQL Server in mixed mode, it is very important that you know your SA password.
There can be different reasons you lost the password
·         Person who installed the SQL Server knows the password but has left the building.
·         You did not write down the password in your password file
·         Password file is lost
Steps to recover the SA password:

1.    Start SQL Server Configuration Manager

    2.    Stop the SQL services

    3.   Edit the properties of the SQL Service

    4.   Change the startup parameters of the SQL service by adding a –m; in front of the existing parameters.


    5. Start the SQL services. These are now running in Single User Mode

    6. Start CMD on tthe SQL server

    7. Start the SQLCMD command. Now you will see following screen.

    8.Now we create a new user. Enter following commands

            CREATE LOGIN crmuser WITH PASSWORD = 'hcl@123'

   CREATE LOGIN [Login_name] FROM WINDOWS WITH DEFAULT_DATABASE=[master]

 9.  Now we grant the user a SYSADMIN roles using the same SQLCMD window.
         
                        sp_addsrvrolemember ‘crmuser’, ‘sysadmin’
                        go

          EXEC master..sp_addsrvrolemember @loginame = 'login_name',
          @rolename = 'sysadmin'



10.  Stop the SQL service again


11.  Change the SQL service properties back to the default settings.

 12.  Start the SQL server and go via the security panel to the properties and change the password of the SA   
       account.

   ‘sa’ because the account is currently locked out:

  Fix/Solution/Workaround:

1.       Disable the policy on your system or on your domain level. However, this may not be the most 
       appropriate option as it will adversely affect your security protection level.

2.        If this is a one-time issue, enable “sa” login WITH changing password of “sa” login.

        ALTER LOGIN  sa  WITH PASSWORD = 'yourpass' UNLOCK ;
        GO

3.       If this is a one-time issue, enable “sa” login WITHOUT changing password of “sa” login.

       ALTER LOGIN sa WITH CHECK_POLICY = OFF;



WMI Error

SQL Server Configuration Manager – Cannot connect to WMI provider – Provider load failure [0x80041013]


As soon as he was trying to launch SQL Server Configuration Manager, he was seeing below error.

This problem occurs when we have installed both 32 bit version and 64 bit version of SQL Server on same Windows Machine and when we uninstall an instance of SQL Server,  WMI provider is also removed.The 32-bit instance and the 64-bit instance of SQL Server share the same WMI configuration file. This file is located in the %programfiles(x86)% folder.
To Resolve this issue, we need to locate the file “Sqlmgmproviderxpsp2up.mof” which is present at the
"%programfiles(x86)%\Microsoft SQL Server\number\Shared folder"

The value of number depends on the version of SQL Server
Microsoft SQL Server 2012
110
Microsoft SQL Server 2008 R2
100
Microsoft SQL Server 2008
100
hen, from Command Prompt we need to run below command.
mofcomp “%programfiles(x86)%\Microsoft SQLServer\number\Shared\sqlmgmproviderxpsp2up.mof”




Wednesday, 6 May 2015

DBCC CHECKDB

Checks the logical and physical integrity of all the objects in the specified database by performing the following operations:
·         Runs DBCC CHECKALLOC on the database.
·         Runs DBCC CHECKTABLE on every table and view in the database.
·         Runs DBCC CHECKCATALOG on the database.
·         Validates the contents of every indexed view in the database.
·         Validates link-level consistency between table metadata and file system directories and files when storing varbinary(max) data in the file system using FILESTREAM.
·         Validates the Service Broker data in the database.

DBCC CHECKDB is supported on databases that contain memory-optimized tables but validation only occurs on disk-based tables. However, as part of database backup and recovery, a CHECKSUM validation is done for files in memory-optimized filegroups.
Since DBCC repair options are not available for memory-optimized tables, you must back up your databases regularly and test the backups. If data integrity issues occur in a memory-optimized table, you must restore from the last known good backup.
DBCC CHECKDB 
[
    [ ( database_name | database_id | 0
        [ , NOINDEX 
        | , { REPAIR_ALLOW_DATA_LOSS | REPAIR_FAST | REPAIR_REBUILD } ]
    ) ]
    [ WITH 
        {
            [ ALL_ERRORMSGS ]
            [ , EXTENDED_LOGICAL_CHECKS ] 
            [ , NO_INFOMSGS ]
            [ , TABLOCK ]
            [ , ESTIMATEONLY ]
            [ , { PHYSICAL_ONLY | DATA_PURITY } ]
        }
    ]
]

This means that the DBCC CHECKALLOC, DBCC CHECKTABLE, or DBCC CHECKCATALOG commands do not have to be run separately from DBCC CHECKDB.
-- Check the current database.
DBCC CHECKDB;
GO
-- Check the AdventureWorks2012 database without nonclustered indexes.
DBCC CHECKDB (AdventureWorks2012, NOINDEX);
GO

DBCC CHECKALLOC
Checks the consistency of disk space allocation structures for a specified database.
DBCC CHECKALLOC 
[
    ( database_name | database_id | 0 
      [ , NOINDEX 
      | , { REPAIR_ALLOW_DATA_LOSS | REPAIR_FAST | REPAIR_REBUILD } ]
    )
    [ WITH 
        { 
          [ ALL_ERRORMSGS ]
          [ , NO_INFOMSGS ] 
          [ , TABLOCK ] 
          [ , ESTIMATEONLY ] 
        }
    ]
]
 
-- Check the current database.
DBCC CHECKCATALOG;
GO
-- Check the AdventureWorks2012 database.
DBCC CHECKCATALOG (AdventureWorks2012);
GO
 
DBCC CHECKCATALOG
Checks for catalog consistency within the specified database. The database must be online.
DBCC CHECKCATALOG 
[ 
    ( 
    database_name | database_id | 0
    )
]
    [ WITH NO_INFOMSGS ] 

-- Check the current database.
DBCC CHECKCATALOG;
GO
-- Check the AdventureWorks2012 database.
DBCC CHECKCATALOG (AdventureWorks2012);
GO
DBCC CHECKTABLE
Checks the integrity of all the pages and structures that make up the table or indexed view.
DBCC CHECKTABLE 
(
    table_name | view_name
    [ , { NOINDEX | index_id }
     |, { REPAIR_ALLOW_DATA_LOSS | REPAIR_FAST | REPAIR_REBUILD } 
    ] 
)
    [ WITH 
        { ALL_ERRORMSGS ]
          [ , EXTENDED_LOGICAL_CHECKS ] 
          [ , NO_INFOMSGS ]
          [ , TABLOCK ] 
          [ , ESTIMATEONLY ] 
          [ , { PHYSICAL_ONLY | DATA_PURITY } ] 
        }
    ]
 
To perform DBCC CHECKTABLE on every table in the database, use DBCC CHECKDB.
For the specified table, DBCC CHECKTABLE checks for the following:
  • Index, in-row, LOB, and row-overflow data pages are correctly linked.
  • Indexes are in their correct sort order.
  • Pointers are consistent.
  • The data on each page is reasonable, included computed columns.
  • Page offsets are reasonable.
  • Every row in the base table has a matching row in each nonclustered index, and vice-versa.
  • Every row in a partitioned table or index is in the correct partition.
  • Link-level consistency between the file system and table when storing varbinary(max) data in the file system using FILESTREAM.

Result set:
DBCC results for 'HumanResources.Employee'.
There are 288 rows in 13 pages for object 'Employee'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.


https://msdn.microsoft.com/en-us/library/ms176064.aspx

Monday, 6 April 2015

Restore .bak file to Database

If I have a .bak file and I want to restore it database what are the various steps involved in it. Assume that I do not know much about that backup file.

‐‐Retrieve logical file name

RESTORE FILELISTONLY FROM DISK = 'D:\wave.bak'
GO

‐‐Make Database to single user Mode

ALTER DATABASE wave SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

‐‐Restore Database

RESTORE DATABASE wave
FROM disk = 'D:\wave.bak'
WITH MOVE 'Best' TO 'd:\wave.mdf',
MOVE 'Best_log' TO 'd:\wave_log.ldf'
GO

‐‐Make Database to multi user Mode

ALTER DATABASE wave SET MULTI_USER
GO


PERMISSIONS AFTER REFRESHING (Restoring)

Run the below script in source server database(which database you want to restore) then we will get the Stored proc of the all the permissions then run these stored proc in destination server new database.

select 'exec sp_addrolemember ' + '''' + g.name + '''' + ',' + '''' + m.name + ''''
from sys.sysmembers join sys.sysusers g on groupuid = g.uid
join sys.sysusers m on memberuid = m.uid

TRANSFER LOGINS TO NEW INSTANCE(REV_LOGIN SCRIPT)

Run the REV_LOGIN(below attached) script in source server master database then we will get the Stored proc of the all the logins then run these stored proc in destination server.


REV_LOGIN SCRIPT:

USE master
GO
IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL
  DROP PROCEDURE sp_hexadecimal
GO
CREATE PROCEDURE sp_hexadecimal
    @binvalue varbinary(256),
    @hexvalue varchar (514) OUTPUT
AS
DECLARE @charvalue varchar (514)
DECLARE @i int
DECLARE @length int
DECLARE @hexstring char(16)
SELECT @charvalue = '0x'
SELECT @i = 1
SELECT @length = DATALENGTH (@binvalue)
SELECT @hexstring = '0123456789ABCDEF'
WHILE (@i <= @length)
BEGIN
  DECLARE @tempint int
  DECLARE @firstint int
  DECLARE @secondint int
  SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
  SELECT @firstint = FLOOR(@tempint/16)
  SELECT @secondint = @tempint - (@firstint*16)
  SELECT @charvalue = @charvalue +
    SUBSTRING(@hexstring, @firstint+1, 1) +
    SUBSTRING(@hexstring, @secondint+1, 1)
  SELECT @i = @i + 1
END

SELECT @hexvalue = @charvalue
GO

IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
  DROP PROCEDURE sp_help_revlogin
GO
CREATE PROCEDURE sp_help_revlogin @login_name sysname = NULL AS
DECLARE @name sysname
DECLARE @type varchar (1)
DECLARE @hasaccess int
DECLARE @denylogin int
DECLARE @is_disabled int
DECLARE @PWD_varbinary  varbinary (256)
DECLARE @PWD_string  varchar (514)
DECLARE @SID_varbinary varbinary (85)
DECLARE @SID_string varchar (514)
DECLARE @tmpstr  varchar (1024)
DECLARE @is_policy_checked varchar (3)
DECLARE @is_expiration_checked varchar (3)

DECLARE @defaultdb sysname

IF (@login_name IS NULL)
  DECLARE login_curs CURSOR FOR

      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM 
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name <> 'sa'
ELSE
  DECLARE login_curs CURSOR FOR


      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM 
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name = @login_name
OPEN login_curs

FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
IF (@@fetch_status = -1)
BEGIN
  PRINT 'No login(s) found.'
  CLOSE login_curs
  DEALLOCATE login_curs
  RETURN -1
END
SET @tmpstr = '/* sp_help_revlogin script '
PRINT @tmpstr
SET @tmpstr = '** Generated ' + CONVERT (varchar, GETDATE()) + ' on ' + @@SERVERNAME + ' */'
PRINT @tmpstr
PRINT ''
WHILE (@@fetch_status <> -1)
BEGIN
  IF (@@fetch_status <> -2)
  BEGIN
    PRINT ''
    SET @tmpstr = '-- Login: ' + @name
    PRINT @tmpstr
    IF (@type IN ( 'G', 'U'))
    BEGIN -- NT authenticated account/group

      SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' FROM WINDOWS WITH DEFAULT_DATABASE = [' + @defaultdb + ']'
    END
    ELSE BEGIN -- SQL Server authentication
        -- obtain password and sid
            SET @PWD_varbinary = CAST( LOGINPROPERTY( @name, 'PasswordHash' ) AS varbinary (256) )
        EXEC sp_hexadecimal @PWD_varbinary, @PWD_string OUT
        EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT

        -- obtain password policy state
        SELECT @is_policy_checked = CASE is_policy_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
        SELECT @is_expiration_checked = CASE is_expiration_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name

            SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' WITH PASSWORD = ' + @PWD_string + ' HASHED, SID = ' + @SID_string + ', DEFAULT_DATABASE = [' + @defaultdb + ']'

        IF ( @is_policy_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_POLICY = ' + @is_policy_checked
        END
        IF ( @is_expiration_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_EXPIRATION = ' + @is_expiration_checked
        END
    END
    IF (@denylogin = 1)
    BEGIN -- login is denied access
      SET @tmpstr = @tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME( @name )
    END
    ELSE IF (@hasaccess = 0)
    BEGIN -- login exists but does not have access
      SET @tmpstr = @tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME( @name )
    END
    IF (@is_disabled = 1)
    BEGIN -- login is disabled
      SET @tmpstr = @tmpstr + '; ALTER LOGIN ' + QUOTENAME( @name ) + ' DISABLE'
    END
    PRINT @tmpstr
  END

  FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
   END
CLOSE login_curs
DEALLOCATE login_curs
RETURN 0
GO


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


EXEC sp_help_revlogin


=======================

ORPHANED USERS? HOW TO FIXED ORPHANED USERS?

When a DB is move, attach & detach, restoring to different instance or corresponding login is dropped, the users of the Database becomes Orphaned users and they can’t access the database because the database users are not mapped to SID (Security Identifier) in the new instance.

To detect Orphaned users:EXEC sp_change_users_login 'Report'

Fix the Orphaned users : EXEC  sp_change_users_login 'Auto_Fix',@tempUsername;


If multiple Orphaned users then :


CREATE TABLE #OrphanedUsers(
row_num  INT IDENTITY(1,1),
username VARCHAR(1000),
id       VARCHAR(1000)

)

INSERT INTO #OrphanedUsers(username,id)
EXEC sp_change_users_login 'Report'

DECLARE @rowCount INT = (SELECT COUNT(1) FROM #OrphanedUsers );

DECLARE @i INT =1 ;
DECLARE @tempUsername VARCHAR(1000);

WHILE(@i <= @rowCount)
BEGIN
               SELECT @tempUsername = username FROM #OrphanedUsers WHERE row_num = @i;

               EXEC  sp_change_users_login 'Auto_Fix',@tempUsername;

               SET @i = @i+1;
END

DROP TABLE #OrphanedUsers;