Thursday, October 31, 2013

Reseeding Identity Columns


This morning I woke up with this question on my mind.  If I reseed an Identity column in a table with existing rows will the new rows account for the existing identity numbers and skip them as it increases the numbers.    The answer is no and here is how I proved it.

First, I created a table that I could test in

CREATE TABLE [dbo].[T_SWL_3](
       [SWL_id] [int] Identity (1,1) not NULL,
       [SWL_Text] [varchar] (50) NULL,
       [SWL_Date] [datetime] NULL DEFAULT (getdate()),
 CONSTRAINT [PK_T_SWL_3] PRIMARY KEY CLUSTERED
(
       [SWL_id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO


This table has an Identity column seeded starting at 1 with an increment of 1.  It also has a date defaulting to the getdate() when the row is inserted. 

Second I placed some rows in the table and deleted a few to create holes in the identity column.

INSERT INTO [dbo].[T_SWL_3]
           ([SWL_Text])
Select 'Test 1'
Union
Select 'Test 2'
Union
Select 'Test 3'
Union
Select 'Test 4'
Union
Select 'Test 5'
Union
Select 'Test 6'
Go

DELETE FROM [dbo].[T_SWL_3]
      WHERE [SWL_id] in (2,4,5)
GO
 

Third, I added some more rows to make sure that Identity would continue and it does.

INSERT INTO [dbo].[T_SWL_3]
           ([SWL_Text])
Select 'Test 1a'
Union
Select 'Test 2a'
Go

SELECT [SWL_id]
      ,[SWL_Text]
      ,[SWL_Date]
FROM [dbo].[T_SWL_3]
GO

At this point, here is what the table looks like.

SWL_id
SWL_Text
SWL_Date
1
Test 1
10/31/13 6:53 AM
3
Test 3
10/31/13 6:53 AM
6
Test 6
10/31/13 6:53 AM
7
Test 1a
10/31/13 6:53 AM
8
Test 2a
10/31/13 6:53 AM

Fourth, I reseeded the table with this command starting back at 1.
DBCC CHECKIDENT ('T_SWL_3', RESEED, 1);


Fifth, I inserted new rows to see what would happen.  It fails and I get this error message.
 

Select 'Test 1c' Item
Union
Select 'Test 2c'  Item
Go

SELECT [SWL_id]
       ,[SWL_Text]
      ,[SWL_Date]
FROM [dbo].[T_SWL_3]
GO

Msg 2627, Level 14, State 1, Line 5

Violation of PRIMARY KEY constraint 'PK_T_SWL_3'. Cannot insert duplicate key in object 'dbo.T_SWL_3'. The duplicate key value is (3).

The statement has been terminated.

The primary key constraint must be unique and when the identity process within SQL Server tries to use 3  it is already there and the insert fails.

Moral of the story, either remove all existing rows before the reseed, renumber the Identities or don’t reseed.   Unfortunately, the identity is generally used as the link between two tables so changing the numbers on data that needs to be retained is probably out of the question because all connecting tables would need to change as well.   One possibility is to start the seed at a very low number and this allows it more room to grow.

Columns that are int could have their seeds starting at -2,147,483,648 and bigints at --9,223,372,036,854,775,808.  If the id is used to just link tables and no one will see it, there is no reason to do this and it doubles your row capacity for the identity column.

Here is what my table looks like if I do that.

CREATE TABLE [dbo].[T_SWL_3](
       [SWL_id] [int] Identity (-2147483648,1) not NULL,
       [SWL_Text] [varchar] (50) NULL,
       [SWL_Date] [datetime] NULL DEFAULT (getdate()),
 CONSTRAINT [PK_T_SWL_3] PRIMARY KEY CLUSTERED
(
      [SWL_id] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO

 
INSERT INTO [dbo].[T_SWL_3]
           ([SWL_Text])
Select 'Test 1'
Union
Select 'Test 2'
Union
Select 'Test 3'
Union
Select 'Test 4'
Union
Select 'Test 5'
Union
Select 'Test 6'
Go
 

SELECT [SWL_id]
      ,[SWL_Text]
      ,[SWL_Date]
FROM [dbo].[T_SWL_3]
GO

SWL_id
SWL_Text
SWL_Date
-2147483648
Test 1
10/31/13 7:03 AM
-2147483647
Test 2
10/31/13 7:03 AM
-2147483646
Test 3
10/31/13 7:03 AM
-2147483645
Test 4
10/31/13 7:03 AM
-2147483644
Test 5
10/31/13 7:03 AM
-2147483643
Test 6
10/31/13 7:03 AM

 

Thursday, October 20, 2011

The Humble GO

When one goes to a conference or training, one never quite knows what else will be learned.  Here is an example from the Professional Association for SQL Server Summit 2011 (PASS 2011) I just attended. 

I did not know that the GO statement, which I have used for years, had the option of adding a count.  This count causes the batch to be run several times.   It works on 2008 R2 as well as 2000. 

In my test database I created a table that has a row with a date column in it.  When I run the code below I get the results that follow.   As shown there are 5 rows that are inserted since the GO after the INSERT has a 5 on it.  The count is increased by 5 rows.


SELECT COUNT(*)
FROM [SWL_TEST].[dbo].[T_SWL]
GO

INSERT INTO [SWL_TEST].[dbo].[T_SWL]
           ([SWL_Date])
     VALUES
           (GETDATE())
GO 5


SELECT COUNT(*)
FROM [SWL_TEST].[dbo].[T_SWL]
GO

Results

-----------
66

(1 row(s) affected)

Beginning execution loop

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)
Batch execution completed 5 times.

-----------
71

(1 row(s) affected)

The example in books online uses a “Hello World” message.  I changed it to PRINT the message and then add a 5 to the GO.

DECLARE @MyMsg VARCHAR(50)
SELECT @MyMsg = 'Hello, World.'
Print @MyMsg
GO 5

Results in

Beginning execution loop
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Hello, World.
Batch execution completed 5 times.

Wednesday, July 27, 2011

Effect of INCLUDES on SQL Server Indexes

The question here is what is the effect of INCLUDES on indexes and their usage.  To test this I created this query
SELECT [AddressID]
      ,[AddressLine1]
      ,[AddressLine2]
      ,[City]
      ,[StateProvinceID]
      ,[PostalCode]
  FROM [AdventureWorks].[Person].[Address]
  Where [PostalCode] = '01071'
My normal testing for performance produced the following.  This shows that there are 31 rows returned.  It needs 216 logical reads to find those 31.
(31 row(s) affected)
Table 'Address'. Scan count 1, logical reads 216, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 9 ms.

(1 row(s) affected)

(1 row(s) affected)
+++++++++++++++++++++++++++
Final Summary - TIME STUDY
+++++++++++++++++++++++++++
Begin Date Jul 13 2011  8:52:36:630AM
Finish Date = Jul 13 2011  8:52:36:643AM
TOTAL Clock TIME (ms) = 13
TOTAL Clock TIME (sec)  = 0.01300
TOTAL Clock TIME (min) = 0.00022
TOTAL Clock TIME (hr) = 0.00000
Rows Processed = 0
TOTAL CPU TIME (ms) = 0
TOTAL CPU TIME (sec)  = 0.00000
TOTAL CPU TIME (min) = 0.00000
TOTAL CPU TIME (hr) = 0.00000
Here is the execution plan for this.  It shows that the index being used does not have the Postal Code in its columns. 
Here is the definition of the index used.
CREATE UNIQUE NONCLUSTERED INDEX [IX_Address_AddressLine1_AddressLine2_City_StateProvinceID_PostalCode] ON [Person].[Address]
(
  [AddressLine1] ASC,
  [AddressLine2] ASC,
  [City] ASC,
  [StateProvinceID] ASC,
  [PostalCode] ASC
)
ON [PRIMARY]
GO
I added the following index because the Postal_Code is used in the WHERE clause.
CREATE NONCLUSTERED INDEX [IX_Address_PostalCode]
ON [Person].[Address]
(
  [PostalCode] ASC
)
ON [PRIMARY]
This changes the results to the following.
 (31 row(s) affected)
Table 'Address'. Scan count 1, logical reads 74, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 16 ms,  elapsed time = 3 ms.

(1 row(s) affected)

(1 row(s) affected)
+++++++++++++++++++++++++++
Final Summary - TIME STUDY
+++++++++++++++++++++++++++
Begin Date Jul 13 2011  8:57:46:190AM
Finish Date = Jul 13 2011  8:57:46:200AM
TOTAL Clock TIME (ms) = 10
TOTAL Clock TIME (sec)  = 0.01000
TOTAL Clock TIME (min) = 0.00017
TOTAL Clock TIME (hr) = 0.00000
Rows Processed = 0
TOTAL CPU TIME (ms) = 31.25
TOTAL CPU TIME (sec)  = 0.03125
TOTAL CPU TIME (min) = 0.00052
TOTAL CPU TIME (hr) = 0.00001
This shows that this simple index reduced the logical reads to 74 or a savings of 142 logical reads.  This is good and an improvement.  Here is the Execution plan which shows the use of two indexes – the new one and the clustered index.
  Adding the various selected columns and a few more to the index was the next test.
CREATE NONCLUSTERED INDEX [IX_Address_PostalCode__AddressID_AddressLine1_AddressLine2_City_StateProvinceID]
ON [Person].[Address]
(
  [PostalCode] ASC
)
INCLUDE ( [AddressID],
[AddressLine1],
[AddressLine2],
[City],
[StateProvinceID],
[rowguid],
[ModifiedDate]) WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
This produced these results
(31 row(s) affected)
Table 'Address'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

(1 row(s) affected)

(1 row(s) affected)
+++++++++++++++++++++++++++
Final Summary - TIME STUDY
+++++++++++++++++++++++++++
Begin Date Jul 13 2011  9:01:17:080AM
Finish Date = Jul 13 2011  9:01:17:087AM
TOTAL Clock TIME (ms) = 6
TOTAL Clock TIME (sec)  = 0.00600
TOTAL Clock TIME (min) = 0.00010
TOTAL Clock TIME (hr) = 0.00000
Rows Processed = 0
TOTAL CPU TIME (ms) = 0
TOTAL CPU TIME (sec)  = 0.00000
TOTAL CPU TIME (min) = 0.00000
The same 31 rows are produced with only 2 logical reads.  This is a savings of 214 logical reads.  This is best.   Also, the simple index still exists and the optimizer selected the new one to use.  Here is the execution plan for this run.

There are two major conclusions.  First the optimizer is smart enough to pick the right index when it is available in this case.  Second, adding Includes to the index improves performance by reducing the number of logical reads.  The cost of this is space used. 

Here is the difference in space between the two indexes in this case.

Index Name
KB
IX_Address_PostalCode
424
IX_Address_PostalCode__AddressID_AddressLine1_AddressLine2_City_StateProvinceID
2,176

This shows the additional space is used to store the Included columns.

Monday, April 4, 2011

Drop not for replication

Our developers created a trigger on a table that is being replicated from another server.  The trigger is on the subscription table.  This trigger inserts rows into three other tables.  When the trigger was placed into production the data stopped flowing and the process threw an error in the replication monitor.  There was an option on the three tables called “Not for Replication”.  The tables had their own identity column.  

The error that we received was
Replication-Replication Distribution Subsystem: agent <Distribution Agent Job Name> failed. Cannot insert duplicate key row in object 'dbo.<Table Name>' with unique index '<index name>'. The duplicate key value is (<Number>).

To fix this issue the tables were altered turning off this option.  It is ironic that this double negative is being used – “Drop not for replication”.  Once the option was turned off and replication restarted the data was replicated as expected.

Here is the code that was used.

Alter TABLE <schema name>.<Table name>
      Alter Column <Identity Column Name> DROP NOT FOR REPLICATION;

Thursday, February 10, 2011

Database Role db_executor

There is no simple way to give permission to run Stored Procedures and Functions within SQL Server.  It would be convenient to have a database role that once assigned to a login permissions would be granted to execute all the code.  Since there is not a built-in role, one needs to be created.  And because code changes over time, a method to grant permissions must be created to easily keep the code’s permissions in place.
First, the simple solution would be to create a database role.  I have called it db_executor.  When stored procedures are changed in anyway as part of the script this statement would grant the permissions.
GRANT EXECUTE ON <Schema name>.<Stored procedure name> TO db_executor
This will give the permissions to db_executor and any users who have that privilege. 
The concern is, if this GRANT statement is missing from an update, the permissions would not be granted if the stored procedure is updated.
This Stored Procedure, created in SQL Server 2008 R2, will generate a database role called “db_exceutor”.  Here is what the procedure does: 
1.      If the db_executor is in the database
a.       The logins associated with it are captured and stored in table variable.
b.      The logins are dropped from the role
c.       The role is dropped
2.      The role is created
3.      All object names that are procedures (P), aggregate functions (AF), SQL scalar functions (FN), Assembly (CLR) scalar-functions (FS), Assembly (CLR) table-valued functions (FT), SQL inline table-valued functions(IF), and SQL table-valued-functions (TF)  and placed in a table variable.
4.      The object names are used to generate GRANT commands for each object.
5.      The logins captured in the first step are added to the role.


Here is the code
Create PROCEDURE [dbo].[PR_Create_n_Update_db_executor]
@DatabaseName sysname
AS  
--===================================================================
-- Stored procedure:  dbo.PR_Create_n_Update_db_executor
-- Function:     Creates db_executor and assigns permissions to all
--          relevant objects
--
-- Returns:
--
-- History:
-- Date              Author                   Description
-- February 9, 2011     S.Lindsay        Initial Creation
--===================================================================

Declare @Logins_LGI TABLE (LGI_ID Int identity(1,1), LGI_Name sysname)
Declare @Objects_OBJ TABLE (OBJ_ID Int identity(1,1), OBJ_Name nVarchar(255))

DECLARE @sSQL VARCHAR(4000)
       ,@Mess VARCHAR(4000)
       ,@SP_Count int
       ,@SPName sysname
       ,@Login_Name sysname        
       ,@Object_Name nVarchar(255)          
       ,@jobcnt int
       ,@subj varchar(100)
       ,@EndDate Datetime
       ,@FirstDate Datetime
       ,@RC INT
       ,@MIN_LGI_ID INT       
       ,@MIN_OBJ_ID INT            
       ,@YEAR INT
       ,@DIF_DAYS INT
       ,@RoleMemberName sysname
       ,@RoleName sysname
      
      
set @RoleName = N'db_executor'
SET @SPName = 'PR_Create_n_Update_db_executor'

IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = @RoleName AND type = 'R')
Begin

  Insert @Logins_LGI(LGI_Name)
  select [name]
  from sys.database_principals
  where principal_id in (
       select member_principal_id
       from sys.database_role_members
       where role_principal_id in (
            select principal_id
            FROM sys.database_principals where [name] = @RoleName  AND type = 'R' ))
  SET @MIN_LGI_ID = 0
  Select    @MIN_LGI_ID = Min(LGI_ID)
  FROM @Logins_LGI            
  Where LGI_ID > @MIN_LGI_ID
 
  Select    @Login_Name = LGI_Name
  FROM @Logins_LGI            
  Where LGI_ID = @MIN_LGI_ID  

  WHILE @MIN_LGI_ID is Not null
       BEGIN
            exec sp_droprolemember  @rolename = @RoleName
                                         ,@membername = @Login_Name
            Select    @MIN_LGI_ID = Min(LGI_ID)
            FROM @Logins_LGI            
            Where LGI_ID > @MIN_LGI_ID
           
            Select    @Login_Name = LGI_Name
            FROM @Logins_LGI            
            Where LGI_ID = @MIN_LGI_ID  

       END;
  DROP ROLE [db_executor];
END

CREATE ROLE [db_executor] AUTHORIZATION [dbo]

Insert @Objects_OBJ (OBJ_Name)
SELECT 'USE ' + @DatabaseName + '; GRANT EXECUTE on ' + [name] + ' TO ' + @RoleName + ';'
From sys.objects
Where [TYPE] in ('P', 'AF', 'FN', 'FS', 'FT', 'IF', 'TF')

SET @MIN_OBJ_ID = 0
Select @MIN_OBJ_ID = Min(OBJ_ID)
FROM @Objects_OBJ             
Where OBJ_ID > @MIN_OBJ_ID

Select @Object_Name = OBJ_Name
FROM @Objects_OBJ             
Where OBJ_ID = @MIN_LGI_ID

WHILE @MIN_OBJ_ID is Not null
  BEGIN
       exec master..sp_executeSQL @statement = @Object_Name
       Select    @MIN_OBJ_ID = Min(OBJ_ID)
       FROM @Objects_OBJ           
       Where OBJ_ID > @MIN_OBJ_ID
      
       Select    @Object_Name = OBJ_Name
       FROM @Objects_OBJ           
       Where OBJ_ID = @MIN_OBJ_ID  

  END;

SET @MIN_LGI_ID = 0
Select @MIN_LGI_ID = Min(LGI_ID)
FROM @Logins_LGI         
Where LGI_ID > @MIN_LGI_ID

Select @Login_Name = LGI_Name
FROM @Logins_LGI         
Where LGI_ID = @MIN_LGI_ID

WHILE @MIN_LGI_ID is Not null
  BEGIN
       exec sp_addrolemember   @rolename = @RoleName
                                    ,@membername = @Login_Name
       Select    @MIN_LGI_ID = Min(LGI_ID)
       FROM @Logins_LGI            
       Where LGI_ID > @MIN_LGI_ID
      
       Select    @Login_Name = LGI_Name
       FROM @Logins_LGI            
       Where LGI_ID = @MIN_LGI_ID  

  END;