SQL Server From Squirrel’s View
Lockergnome
Home

Great 3rd Party Tools For SQL Server!

Hi again… yesterday I was evaluating a tool called DBArtisan 8.5.0 by Embarcadero Technologies. Now I have not used this product in the past so I am not able to do a comparison. This tool has a lot of slick, GUI interfaces into SQL Server. So for those of you like myself who like the GUI interface this is a great tool! As I am learning about this tool I have come across one cool feature it is the ability to generate a HTML file from Transact SQL result set. This is helpful when putting this information on an company intranet. I will update this blog with more helpful tidbits as I come across them. You can download the free trial for this tool from Embarcadero here.

The next tool I have in my arsenal is Red Gate’s SQL Compare. Now this tool is a must have for any DBA! This tool has saved me countless of hours comparing database schemas in different environments (development to staging, staging to production). The interface is very straight forward and easy to use. It will also generate and execute the Transact SQL statements to update the schemas in the source or destination databases. Red Gate has this tool available for download here. As I continue to use this tool more I will add more helpful hints. If you have any helpful tidbits please comment and share!

Normal Forms In Relational Database Theory

I was sitting here thinking about what else could I share that other DBAs and developers alike could use or need to know. Then it came to me!… Outside of a specific RDMS it definitely helps to know database theory. So today, I am going to cover Normal Forms or designated as (NF). In theory, as of right now there are 5 Normal Forms. For all practical use however most DBAs and developers take it to 3rd Normal Form. Knowing the Normal Forms and how to apply them will be a tremendous help when design your logical database model.   Edgar F. Codd originally defined the first three normal forms.  I have listed the Normal Forms for you below.

First Normal Form (1NF)
- Exclude variable repeating groups.

Second Normal Form (2NF)
- Meets all requirements of 1NF
- 2NF is violated when a non-key field is a fact about a subset of a key. It is only relevant when the key is composite.

Third Normal Form (3NF)
- Meets all requirements of 2NF
- 3NF is violated when a non-key field is a fact about another non-key field.

Fourth (4NF) and Fifth (5NF) Normal Forms deal with multi-valued facts. e.g. may correspond to a many-to-many relationship

Scripting SQL Server 2005 Logins

I thought today I would share with you a great way to move SQL Server logins from one SQL Server 2005 server (source) to another SQL Server 2005 server (destination).  In the past I have tried to use DTS to move logins (passwords and SIDs) from one server to another but without much success.  As I was surfing the Internet, I came across 2 stored procedures from Microsoft that you create in the master database.  Once compiled, run the primary stored procedure and the result set produces the CREATE LOGIN statements with the correct passwords and SIDs for every login in the source server.  Once this script has been created, you can then copy it and execute the script in a query window on the destination server.  Once you restore the user databases from the source server to the destination server the SIDs found in the user database will then be sync’d to the logins in the master database. 

You will find both stored procedures below in one script.  The primary stored procedure you execute to generate the CREATE LOGIN script is the stored procedure:  sp_help_revlogin   Here is the correct syntax to run the procedure for ALL logins.  exec sp_help_revlogin

Here is the script with the 2 stored procedures:

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

/*
**********************************************************************
**
** Object Name: sp_hexadecimal
** Object Type: Stored Procedure
** File Name: sp_hexadecimal.sql
** Database Name: master
** Author: < Name of the person who wrote the T-SQL
** script >
** Creation Date: 07.10.08 - use ANSI format
** Description: This procedure is involved in scripting out
** logins, passwords and SIDs in SQL Server 2005.
** Special Note: This script is also available from the
** Microsoft website.
** Modified Tables: None
** Called Procedures: None
** Called Jobs: None
** Called UDFs: None
** Calling Procedures: sp_help_revlogin
** Calling Jobs: None
** Calling UDFs: None
** Return Statuses: @hexvalue as OUTPUT
**
**********************************************************************
*/

– Declaration section
DECLARE @charvalue VARCHAR(514)
DECLARE @i INT
DECLARE @length INT
DECLARE @hexstring CHAR(16)

– Initialization section
SELECT @charvalue = ‘0x’
SELECT @i = 1
SELECT @length = DATALENGTH(@binvalue)
SELECT @hexstring = ‘0123456789ABCDEF’

WHILE (@i <= @length)
BEGIN
– Declaration section
DECLARE @tempint INT
DECLARE @firstint INT
DECLARE @secondint INT

– Initialization section
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

/*
**********************************************************************
**
** Object Name: sp_help_revlogin
** Object Type: Stored Procedure
** File Name: sp_help_revlogin.sql
** Database Name: master
** Author: < Name of the person who wrote the T-SQL
** script >
** Creation Date: 07.10.08 - use ANSI format
** Description: This procedure creates the actual T-SQL ‘Create
** Login’ statement with the information from
** the security tables in SQL Server 2005.
** Special Note: This script is also available from the
** Microsoft website.
** Modified Tables: None
** Called Procedures: sp_hexadecimal
** Called Jobs: None
** Called UDFs: None
** Calling Procedures: None
** Calling Jobs: None
** Calling UDFs: None
** Return Statuses: None
**
**********************************************************************
*/

– Declaration section
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)

IF @login_name IS NULL
DECLARE login_curs CURSOR FOR
SELECT
p.sid,
p.[name],
p.[type],
p.is_disabled,
l.hasaccess,
l.denylogin
FROM sys.server_principals AS p
LEFT JOIN sys.syslogins AS 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,
l.hasaccess,
l.denylogin
FROM sys.server_principals AS p
LEFT JOIN sys.syslogins AS 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, @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’
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

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 has 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, @hasaccess, @denylogin

END

CLOSE login_curs
DEALLOCATE login_curs

RETURN 0
GO

Getting Space Used For Tables

I have been looking for a more efficient way of getting space used requirements for all of my tables in a given database.  It seems like Microsoft has answered my prayers.  Microsoft has now given us the sp_MSforeachtable stored procedure.  This procedure is not currently documented within BOL.  The T-SQL script below demonstrates how to use this procedure to retrieve space utilization for all tables within a given database.  If you have a better or different way please post and let us know!

CREATE TABLE #TemptableforspaceUsed
(name SYSNAME,
rows bigINT,
reserved VARCHAR(20),
data VARCHAR(20),
index_size VARCHAR(20),
unused VARCHAR(20))
GO
INSERT #TemptableforspaceUsed
EXEC sp_MSforeachtable ’sp_spaceused ”?”’

update #TemptableforspaceUsed
set reserved=replace (reserved,’KB’,”)

select top 10 name, reserved

from #TemptableforspaceUsed

order by convert(bigint,reserved) desc
drop table #TemptableforspaceUsed

Documentation Header For Your Scripts

Hello there!

I thought today I would share with you the documentation header that I use for my T-SQL scripts. The header has evolved from the days of just the name of the script, the author and the date. Through my years of experience I have made the header more descriptive and always looking to improve it. The header has saved me lots of time from searching through my T-SQL code to see if a particular stored procedure is called, user defined function, etc. Here is the documentation header I use:

/*
**********************************************************************
**
** Object Name: < Object Name>
** Object Type: < Stored Procedure, User Defined Function, etc. >
** File Name: < Name of the file.. normally followed by .sql >
** Database Name: < The name of the database the object will reside in >
** Author: < Name of the person who wrote the T-SQL script >
** Creation Date: < Date the T-SQL script was created with ANSI date >
** Description: < Detailed description of what the script does >
** Special Note: < Any special remarks about the script >
** Modified Tables: < List tables that the data is modified by this script >

** Called Procedures < List procedures that this script calls >
** Called Jobs: < List SQL Agent jobs that this script calls >
** Called UDFs: < List user defined functions that this script calls >
** Calling Procedures: < List procedures that call this script >

** Calling Jobs: < List SQL Agent jobs that call this script >
** Calling UDFs: < List User Defined Functions that call this script >
** Return Statuses: < List return status that this script returns >
**
**********************************************************************
*/

If you would like to suggest adding something more to the document header please comment!

Identify Version Number, Service Pack And Edition For SQL Server 2005

Hello and welcome back!

Today I am going to cover how easily it is to verify the version number, service pack and edition that is installed on SQL Server 2005. When you run the following T-SQL statement it will give you the Product Version, Product Level and the Edition.

Step 1 - Connect to a valid SQL Server 2005 server.

Step 2 - After connecting, open up a query window. It does not matter what database is specified when opening up the query window.

Step 3 - Type and execute the following T-SQL statement:

SELECT SERVERPROPERTY(‘productversion’) AS [Product Version], SERVERPROPERTY (‘productlevel’) AS [Product Level], SERVERPROPERTY (‘edition’) AS [Edition]

This will give you the detailed information you are looking for. If you have another way of identifying this information please post your solution!

Removing Transactions That Are Marked For Replication

Hello once again… today I am covering how to remove transactions that are marked for replication in the transaction log of a restored database. Now I have seen this occur in SQL Server 2000 so many times that I have created a T-SQL script that I execute step by step to ‘unmark’ these transactions so that I am able to shrink the log of the restored database.

Here is the scenario… there is a production database that is involved in replication and the developers want to restore the backup of this database to a development server to develop against. This database will no longer participate in replication while residing on the development server. Once the production database gets restored to the development server the database is still ‘marked’ for replication as well as the transactions that were in the log at the time of the full database backup. Now in order to conserve space on the development server the log needs to be shrunken down. When a DBCC ShrinkDatabase or DBCC ShrinkFile is executed on the database the transaction log does not truncate and the log does not shrink. This is what we do to fix this…

Step 1 - Make sure that the Recovery Model for the restored database is set to ‘Full’.

Step 2 - Make sure in the master.dbo.sysdatabases table (on the development server) that the category column for the restored database is set to 1 (the database is marked for replication).

Step 3 - Run the following T-SQL script in the restored database:

EXEC sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0, @time = 0, @reset = 1

This will ‘unmark’ the transactions (for replication) in the log

Step 4 - Backup the Log

BACKUP LOG <database name> WITH NO_LOG

Step 5 - Shrink the log

USE <database name> DBCC SHRINKFILE (N’<database name>_log’)

The log will now be down to a size reasonable size. To keep your log small on the development server, set the Recovery Model to ‘Simple’. Let me know how this process works for you!

Database Mirroring In SQL Server 2005

Welcome back to squirrel’s blog on “everything” SQL Server. I will be covering little nuances with Database Mirroring here. Database Mirroring is a very cool feature in SQL Server 2005 when you get it setup and configured properly. I went through the growing pains of installing, configuring and troubleshooting this process.

Before I installed it on my production database servers I used an application called VM Workstation - http://www.vmware.com. With this cool software I was able to create the production SQL Servers (here you will need the Windows and SQL Server ISOs) but in a virtual form. My production database servers have Windows 2003 Server and SQL Server 2005. Once I got 3 (Principal server, Witness server, Mirror server) virtual machines\servers setup I went ahead and installed and configured Database Mirroring. Import thing to note… you will need to install SQL Server 2005 Service Pack 1 or later for database mirroring to work. Database Mirroring is disabled by default.

When setting up the servers to participate in the mirroring process it is import to fully qualify the server name e.g. mycompname.mydomainname in order for Database Mirroring to see the servers. I tried it using the IP Addresses but Database Mirroring did not like that. Also, fortunate for me all of my servers were in the same domain. If anyone has experience going across different domains please share your experience. Last thing to note on Database Mirroring… when using a Witness server if there is a ‘hick up’ in the network the Witness will view that as a failure in the communication between the Principal and Mirror servers and will automatically “fail” it over to the mirror server. For this reason, I have left the Witness server out of the configuration and just have the Principal server and the Mirror server. If there is a production problem then you can fail it over manually.

For more information on Database Mirroring please see BOL.

Greetings From SQLSquirrel!

Hello..

Welcome to my blog… this blog is dedicated to providing information that is not found in your standard SQL Server books. Through my years of experience I have collected numerous tips and tricks to help get through those rough times when trying to get a project pushed into production. This blog will discuss tips and tricks from SQL Server 7.0 through SQL Server 2005.

As I provide these tips and tricks I will point out which version(s) of SQL Server they will work on. I invite you the reader to comment and perhaps donate tips and tricks from your own experience. I like to call it… SQL Server Tips and Tricks from the field.

1 2 3 4 5 ... 999999