SP_SPACEUSED is giving wrong counts

Udayarumilli_DBCCSP_SPACEUSED is giving wrong counts !!!

SP_SPACEUSED: is a system stored procedure and used to capture number of rows, total size, data and index size information. Sometimes SP_SPACEUSED may give incorrect information or SP_SPACEUSED  give wrong counts. Below are some of the reasons those may leads to give the wrong page / row counts in SP_SPACEUSED. This may because of below reasons.

  1. Statistics are not updated for a long time

  2. Index maintenance is not being organized

  3. Huge number of DDL operations

If you find a wrong result from SP_SPACEUSED, follow the below instructions to resolve this issue.

  1. Run DBCC UPDATEUSAGE

  2. Rebuild indexes

DBCC UPDATEUSAGE: It reports and corrects inaccurate page and row count information in catalog views. These inaccurate values may impact the result of SP_SPACEUSED.

“DBCC UPDATEUSAGE” corrects the rows, used pages, reserved pages, leaf pages and data page counts for each partition in a table or index.

This command can run over a specific database, table or index.

Example:

USE udayarumilli;
GO
DBCC UPDATEUSAGE(0);

Run DBCC UPDATEUSAGE on entire database:

USE udayarumilli;
GO

-- Running command on entire database "udayarumilli"
DBCC UPDATEUSAGE('udayarumilli');

Run DBCC UPDATEUSAGE on a specific Table:

USE udayarumilli;
GO

-- Running command on a specific table "Product_NewID"
DBCC UPDATEUSAGE('udayarumilli','[Product_NewID]');

Run DBCC UPDATEUSAGE on a specific index:

USE udayarumilli;
GO

-- Running command on a specific index "ix_Product_NewID_ID"
DBCC UPDATEUSAGE('udayarumilli','[Product_NewID]','ix_Product_NewID_ID');

Precautions:

  1. It’s not supposed to run this command on frequent basis on sql instance with 2005 or later versions.

  2. Can execute onetime if we find issues with SP_SPACEUSED results

  3. Can schedule to execute weekly basis only if database undergoes DDL modifications.

 Have a look here for more details.

Posted in SQL Development | Tagged , , , , , , , , | 1 Comment

How to generate script for multiple objects in a database – SQL Server

udayarumilli_SQLScript

Generating script for Stored procedures and views in SQL Server 2012

Today I have got a question from one of the beginner DBA. He was actually asked to get “CREATE SCRIPT” for 35 stored procedures and 15 views from one of the database.  He started trying to get script for each object one by one and as he doesn’t have clue how to get the task done in a single go.

It may sounds silly for the experienced people but I believe this blog can help the beginners. Now let’s see how to generate script for multiple objects in a database – SQL Server.

To demonstrate this I have created few dummy stored procedures and views.

Now let’s see how to take the “CREATE SCRIPT” for all selected objects.

  1. Right click on Database name (My database name is “udayarumilli”) , click on “Tasks” and click on “Generate Scripts”

  1. A new window opens with the introduction page just click on Next button.

  1. There are two options available,

“Script entire database and all database objects” and

“Select specific database object”.

As we are looking to script the specific objects select the second option and then select the list objects those needs to be script out. To do that expand the object type node and select the required objects. For example to select the “Test_v_1” expand the object type “Views” and select the required view “Test_v_1”.

  1. Once you selected required objects click on next button. It takes you to the next section “Scripting Options”.

There are different save options available I usually choose “Save to New Query Window”. Apart from this we have two more save options “Save to File” and “Save to Clipboard” we can choose either of these depends on the requirement.

  1. Now on the same page click on “Advanced” button to change the scripting configurations.

Once you click on “Advanced” button there will be a new window opens and there you find two group of options “General” and “Table/View Options”. In all of them we usually concentrate on below options.

“Script DROP and CREATE” : There are three options available depends on requirement we can choose one option whether script required for dropping objects, creating objects or drop and creating the object.

“Script for Server Version”: Depends on which server we are going to run this script we can choose the server version from SQL Server 2000 to 2012”.

“Script USE Database”:  Depends on whether we require this statement at the top of the script or not we can choose “True” or “False”. Usually the database names similar at source and destination so we choose “True”.

  1. Click on “OK” and then “Next” button. It takes you to the “Summary” phase. Cross check the objects selected and configure options and click on “Next” button.


  1. You can check the script at new query window that was generated by “Script Generator”.

  2. You can check the report on object wise. This report is really useful when we do script for bulk number of objects.

  3. Save the report to your local and open it in internet explorer as below.


  1. Go to the query window; once you check the script execute it at the destination machine or save it to a file.

  2. Click on “Finish” button to close the window.

Posted in SQL Development | Tagged , , , , , , , , , | Leave a comment

Difference between NEWID() and NEWSEQUENTIALID() in SQL Server

udayarumilli_uniqueDifference between NEWID() and NEWSEQUENTIALID() in SQL Server

Both NEWID() and NEWSEQUENTIALID() are used to generate GUID of data type UNIQUEIDENTIFIER in SQL Server.

The Basic difference between them is NEWID() generates GUID’s in random order whereas NEWSEQUENTIALID()  generates GUID’s in a sequential order.

We can generate a GUID just by calling NEWID() but we can’t directly use NEWSEQUENTIALID() for generating GUID’s from select statement.

Since NEWID() generates random GUID’s it leads to have more page splits in indexes compare to NEWSEQUENTIALID().

Examples:

  1. Now let’s see how both of them generates GUID’s    

To understand them properly lets create a table insert data and create cluster indexes.

/****** Drop the table if exists ******/
IF EXISTS (SELECT 1 FROM sysobjects WHERE TYPE = 'U' and NAME = 'Product_NewID')
BEGIN
    DROP TABLE Product_NewID;
END
GO
/****Create table with NEWID() ***/
CREATE TABLE Product_NewID(
    ProductID    UNIQUEIDENTIFIER DEFAULT(NEWID()),
    ProductName    VARCHAR(100) NOT NULL,
    ProductPrice    DECIMAL(10,3) NOT NULL DEFAULT(0.000),
    UpdatedDate    DATETIME NOT NULL DEFAULT(SYSDATETIME())
);
GO
IF EXISTS (SELECT 1 FROM sysobjects WHERE TYPE = 'U' and NAME = 'Product_NewSEQID')
BEGIN
    DROP TABLE Product_NewSEQID;
END
GO

/****Create table with NEWSEQUENTIALID() ***/
CREATE TABLE Product_NewSEQID(
    ProductID    UNIQUEIDENTIFIER DEFAULT(NEWSEQUENTIALID()),
    ProductName    VARCHAR(100) NOT NULL,
    ProductPrice    DECIMAL(10,3) NOT NULL DEFAULT(0.000),
    UpdatedDate    DATETIME NOT NULL DEFAULT(SYSDATETIME())
);
GO

/**** Create clustered indexes as below ****/
CREATE CLUSTERED INDEX ix_Product_NewID_ID ON Product_NewID(ProductID);
GO
CREATE CLUSTERED INDEX Product_NewSEQID_ID ON Product_NewSEQID(ProductID);
GO

/*** Now insert data into these two tables ****/
INSERT INTO Product_NewID (ProductName,ProductPrice)
VALUES ('Product_11109',233.56);
GO 20000

INSERT INTO Product_NewSEQID (ProductName,ProductPrice)
VALUES ('Product_11109',233.56);
GO 20000

Now we’ll see just by selecting data from them

You can see all “ProductID” column values are randomly generated.

Now we’ll look into the other table where we have used NEWSEQUENTIALID().

From the above picture we can see the “ProductID” values are sequentially generated.

  1. Now we‘ll see how these differentiate with the select statement.

SELECT NEWID();
GO
SELECT NEWSEQUENTIALID();
GO

NEWID() is generating a GUID. We’ll try with NEWSEQUENTIALID()

It results into an error message:

Msg 302, Level 16, State 0, Line 1

The newsequentialid() built-in function can only be used in a DEFAULT expression for a column of type ‘uniqueidentifier’ in a CREATE TABLE or ALTER TABLE statement. It cannot be combined with other operators to form a complex scalar expression.

  1. Difference between NEWID() and NEWSEQUENTIALID() in page allocation

 We have already inserted 20000 rows into two tables.

Product_NewID: Used NEWID()

Product_NewSEQID: Used NEWSEQUENTIALID()

DBCC SHOWCONTIG('Product_NewID');

 

DBCC SHOWCONTIG('Product_NewSEQID');

 

For the same 20000 rows inserted in these tables we can check observe how pages are allocated for each of these tables.

For the table Product_NewID

Pages Scanned: 218

Avg. Bytes free per page: 2499.7

For the table Product_NewSEQID

Pages Scanned: 152

Avg. Bytes free per page: 69.2

From the above values we can say that there is higher fragmentation for the table which is using NEWID() when comparing with the table which is using NEWSEQUENTIALID().

Posted in SQL Development | Tagged , , , , , , , , , , , , , | Leave a comment