Category: SQL Server

  • Transfer SQL Server Logins Between instances of SQL Server 2005, 2008 or 2008R2

    If you find yourself needing to transfer your SQL Server Logins between instances or SQL servers (SQL Server 2005, 2008, and 2008R2) for migration purposes, or simply want to make a backup of your SQL Server Logins for disaster recovery purposes just follow these easy steps:

    Step 1: On the source server launch SQL Management Studio & connect to the instance of SQL from which you moved the database.

    Step 2: Open Query Editor and run the following:

    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

    This script will create two SP’s (stored procedures) in your master database called “sp_hexadecimal” & “sp_help_revlogin“.

    Step 3: Clear Query Editor & run the following statement:

    EXEC sp_help_revlogin

    Step 4: Copy the output script generated by sp_help_revlogin and either save to file or run this on your new server, this script creates logins that have the original SID (Security Identifier) and password.

    If you want to read more check out the following Microsoft Knowledge Base article: http://support.microsoft.com/kb/918992

    You’re done already – I told you it was easy!

    Jason Vigus
  • Change SQL 2008R2 Server Collation Setting on Failover Cluster

    Many people believe to change the default SQL Server collation setting from the one chosen when SQL Server was originally installed requires SQL Server to be re-installed again, this is not true from SQL 2005 onwards as I shall explain using SQL 2008R2 (in a cluster configuration) as an example.

    To change the default SQL Server collation you can simply rebuild the system databases. When you rebuild the master, model, msdb and tempdb system databases, the databases are actually dropped and recreated in their original location. If a new collation is specified in the rebuild statement the system databases are rebuilt using that collation setting. Any user modifications to theses databases will be lost so it is important to backup any of this you wish to retain, eg SQL Server logins.

    If you are running a non-clustered (standalone) SQL Server, you can simply skip step 3.


    Step 1: Review the Microsoft MSDN documentation regarding “Before You Rebuild The System Databases” & complete the steps to backup your server configuration.

    Step 2: Backup your SQL server logins. (How to Backup/Transfer your SQL Logins)

    Step 3: Open Cluster Failover Administrator & put your SQL Server resource offline, I also recommend you pause the secondary node to prevent any accidental failovers & the resource coming online.

    Step 4: Login to the active SQL node in the cluster & run the following command:
    setup.exe
    /Q
    /ACTION=REBUILDDATABASE
    /SQLSYSADMINACCOUNTS=”DomaineName\UserAccount”
    /SQLCOLLATION=CollationName
    /INSTANCENAME=”OnlyInstanceName”
    /SAPWD=StrongPassword

    Note the following:
    -The INSTANCENAME parameter takes only the SQL server instance, without any server/virtual name, the default instance will be MSSQLSERVER.
    -The SA password must meet strong password requirements
    -The SAPWD parameter is required if the instance it to use mixed mode authentication.
    -The SQLCOLLATION parameter must be set to a correct SQL Collation: http://msdn.microsoft.com/en-us/library/ms180175.aspx 

    Step 5: Apply the required service packs & cumulative updates to bring SQL server back to the correct patch level.

    You can also simply change the database collation settings for individual databases, this is sometimes suitable rather than changing the default server collation for the entire SQL server.

    Troubleshooting:
    If you run the command from “C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\SQLServer2008R2\” and experience the following error when rebuilding the system databases in SQL 2008R2 “Exception has been thrown by the target of an invocation”, the work around is to run the command using the setup.exe which exists on the local media (installation disc).

    Jason Vigus
  • Determine Sharepoint version using SQL query on the Sharepoint config database

    We recently had a client who lost their Sharepoint application (web front-end) server, fortunately their Sharepoint databases were located on a different SQL server (which was being backed up). So we started to rebuild the Sharepoint application server & proceeded to restore the content (websites).

    When we ran through the Sharepoint configuration wizard which connects the application server to the Sharepoint config database it failed at step 2 with the following error:
    “failed to connect to the configuration database an exception of type system.security.securityexception was thrown.
    Additional exception information: access denied”

    This seemed strange since we were definitely using the correct Sharepoint database user, to be sure we verified the permissions were correct in SQL. It turned out the problem is caused by the Sharepoint config database version running a slightly different version to the application server (they need to be exactly the same).

    How did we determine the Sharepoint version of the configuation database then?

    Simple…..

    The first way is to open a web browser and got to the site settings page (Site Actions > Site Settings > Modify All Settings).

    The second method is to run a query against the databases.  Open SQL Server Management Studio, Connect to the server, new query, run the following:

    SELECT [VersionId]
          ,[Version]
          ,[Id]
          ,[UserName]
          ,[TimeStamp]
          ,[FinalizeTimeStamp]
          ,[Mode]
          ,[ModeStack]
          ,[Updates]
          ,[Notes]
      FROM [SharePoint_Config].[dbo].[Versions] 
      WHERE VersionId = ‘00000000-0000-0000-0000-000000000000’ 
      ORDER BY Id DESC

     This returns:

    VersionId Version Id UserName Updates
    00000000-0000-0000-0000-000000000000 12.0.0.6219 4 MOSS\user 3
    00000000-0000-0000-0000-000000000000 12.0.0.4518 1 MOSS\user 2

    The top row is the latest version, if you have changed the database name from “SharePoint_Config” be sure to update the query to reflect the correct name. Check out this site to see what version you are running.

    Once we determined the correct version we created the slipstreamed Sharepoint installation required, re-ran setup and bang everything worked correctly!

    Jason Vigus