h1

SQL SERVER: Community Tech Days in our City at Ahmedabad on 3rd October 2009

09/15/2009
Microsoft Community Tech Days are in 11 cities in INDIA with 19 insightful Technical Sessions.

These insightful Technical sessions are available in our city “Ahmedabad”, Gujarat on 3rd October 2009.

So book your calendar for this day and be a part of this TechDays.

Limited seats are available , so please register yourself with this event:

You can find Register link at: http://www.SQLYoga.com

Let me know if you have any problem in registrations.

h1

SQL SERVER: Check if Node exists in XML or not

08/12/2009

Today, I have one requirement to check dynamically if a node exists in my xml or NOT.

I have a stored procedure that receives XML and I need to check if the message information xml contains one Node or NOT. If that node exists then I need to execute that Stored Procedure by different logic and if not it should run with different logic.

I figure it out by using EXISTS.

This is my XML, that I got as parameter.

DECLARE @ExportData  XML
SELECT @ExportData =
'<Data Number="A123">
  <BulkData>
    <EachData Parts="Test1" />
    <EachData Parts="Test2" />
    <EachData Parts="Test3" />
  </BulkData>
</Data>'

Now I need to check if “BulkData” node exists in XML, then I need to write different logic to get the result.
So, I used this

SELECT @ExportData.exist('(//BulkData)')

This will return “1” if node is exists else return “0”.

That’s it. I can write based on the return result by this statement.

Let me know if it helps you.

Reference : Tejas Shah (http://www.SQLYoga.com)

h1

SQL SERVER: Use CONTEXT_INFO

07/31/2009

Recently I have situation where I have following situation:

I don’t need to execute of trigger’s code, if it is called from particular stored procedure. If data is being updated by from any other places, like application, or any other stored procedures, trigger code should be executed.

I search and I got the option CONTEXT_INFO with SQL SERVER. Let me share this with all of you.

We can use value stored in CONTEXT_INFO in that session only. If there is new session we cannot use that value stored in CONTEXT_INFO.

We can set CONTEXT_INFO up to 128 bytes of binary information with the current session or connection.

Let see an example, for better understanding:

CREATE TABLE tblA(
ID INT IDENTITY,
ColVal VARCHAR(100)
)
Let’s create two SPs, which will insert a record into tblA, which is just created

CREATE PROC TestA
AS
BEGIN
INSERT INTO tblA(ColVal)
SELECT 'Allow To insert'
END

CREATE PROC TestB
AS
BEGIN

DECLARE @UID VARBINARY(128)
SELECT @UID = CAST('TestB' AS VARBINARY(128))
SET CONTEXT_INFO 0x5465737442


INSERT INTO tblA(ColVal)
SELECT 'Not Allow To insert'

END

In this example, when we execute SP: TestA, it should allow to insert record in the table, while we execute SP: TestB, it should restrict. Here I set CONTEXT_INFO with SPName. I can use the same whatever is stored in CONTEXT_INFO during the current session.

To make validation as defined above, lets create one trigger to restrict/allow user to proceed.

CREATE TRIGGER trg_TblA
ON tblA
AFTER INSERT,DELETE,UPDATE
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Message varbinary(128)
SELECT @Message = cast('TestB' as varbinary(128))

IF @Message = CONTEXT_INFO() BEGIN
RAISERROR('Not Allowed to Insert/Update/Delete from SP: TestB',15,1)
ROLLBACK TRAN
END

END
GO

In Trigger, as you can see, I again converted the SP name and compare it with CONTEXT_INFO.

When Stored Procedure TestA is being executed, CONTEXT_INFO is not set, so trigger will not find comparison and allows user to insert record.

While we execute TestB, as we have set CONTEXT_INFO, system will find comparison in trigger and restrict us to complete transaction. So system will give error message:

So, by this way we can validate value in trigger, to make such decision

h1

SQL SERVER: Reset Setup Values, when SQL SERVER is started/restarted

07/15/2009
We have a requirements to clear all setup values when SQL SERVER is started/restarted and we need to setup default values to setup table.

I found one Stored Procedure provided by MS SQL SERVER. Let me share it with all of you.

SQL SERVER provides this SP: “sp_procoption”, which is auto executed every time when SQL SERVER service has been started. I found this SP and it helps me to figure it out the solution for the request as following way. Let me show you how to use it

Syntax use this SP:

EXEC SP_PROCOPTION     
@ProcName = 'SPNAME',    
@OptionName = 'startup',    
@OptionValue = 'true/false OR on/off'

@ProcName, should be Stored procedure name which should be executed when SQL SERVER is started. This stored procedure must be in “master” database.

@OptionName, should be “startup” always.
@OptionValue, this should be set up to execute this given sp or not. If it is “true/on”, given sp will be execute every time when SQL SERVER is started. If it is “false/off”, it will not.
That’s it, lets take an example.
I have one Database called Test, I have created setup table:
CREATE TABLE SetupTable(
Seq INT IDENTITY,
Code VARCHAR(100)
)

Lets insert some default values to this table:

INSERT INTO SetupTable VALUES('A')
INSERT INTO SetupTable VALUES('B')
INSERT INTO SetupTable VALUES('C')
INSERT INTO SetupTable VALUES('D')

What I need to do is, I need to wipe out this values when SQL SERVER is started and fill it with the same default values, because these values might be updated by application.So, I created one stored procedure in master database, named,

CREATE PROC ClearAllData AS

DELETE
FROM    Test.dbo.SetupTable

INSERT INTO SetupTable VALUES('X')
INSERT INTO SetupTable VALUES('Y')
INSERT INTO SetupTable VALUES('Z')

and set up this stored procedure as auto executed every time when SQL SERVER is started as:

EXEC SP_PROCOPTION     
              @ProcName = 'ClearAllData',   
              @OptionName = 'startup',   
              @OptionValue = 'true'
Now, restart SQL SERVICES, and you find that old values will be deleted and new values with ‘X’, ‘Y’, and ‘Z’ will be inserted automatically.
If now you want to stop it to execute automatically, we just need to execute this with “false” as:
EXEC SP_PROCOPTION     
               @ProcName = 'ClearAllData',    
               @OptionName = 'startup',   
               @OptionValue = 'false'
I hope this is very clear to use this feature.
Reference : Tejas Shah (http://www.SQLYoga.com)
h1

SQL SERVER: SQL Query To Find Table Dependencies

04/08/2009
We have very large database and today we want to search the tables which are used mostly.

Means tables which are used in Procedures, Constraints, Views, Triggers etc.

I know this is very strange requirement, but we need to do this.

So, I tried to make an query which will help me to find out the top most tables used in other objects as I mentioned

Let me share that sp with all of you:

SELECT TableName, COUNT(*)
FROM (
Select Distinct
o.Name ‘TableName’,
op.Name ‘DependentObject’
From SysObjects o
INNER Join SysDepends d ON d.DepId = o.Id
INNER Join SysObjects op on op.Id = d.Id
Where o.XType = ‘U’
Group by o.Name, o.Id, op.Name
) x
GROUP BY TableName
ORDER BY 2 desc

So, I made my life easy, by using this. I can get the list if Tables which are used most.

Let me know if it helps you in any way.

h1

SQL SEVER: How to make an Entry in Event Viewer using SQL SERVER

04/02/2009
Today I came across the situation where I need to following scenario.

I need to make entry in Event Viewer when there is an error in Stored Procedure.

I wondered to do this, but finally I come up with the solution. SQL is much powerful.

SQL provides us to make an entry in Event Viewer by two ways:
1. using XP_LogEvent

2. By Raiserror WITH LOG

Lets first see the way using XP_LogEvent:

Here I have created one SP which will raise an error “Divide by zero error encountered.” as I tried to do “10 / 0”.

CREATE PROCEDURE TestEventViewer
AS
BEGIN TRY
    SELECT  10/0
END TRY
BEGIN CATCH
    PRINT ERROR_Message()
    DECLARE @msg VARCHAR(100)
    SELECT @msg = ERROR_Message()

    EXEC xp_logevent 60000, @msg, informational

END CATCH

Lets Execute this SP:

EXEC TestEventViewer

This will write entry in Event Viewer. Now open Event Viewer. You can find Event Viewer at Control Panel –> Administrative Tools –> Event Viewer.

You will get en entry of Error there.

171

So we can do this by Extended Stored Procedure: “xp_logevent”.

Let see the parameters of this Procedure.

First Parameter: “60000” is the Error Number

Second Parameter: “@msg” is the message to be displayed in Event Viewer.

Third Parameter: “informational” is the Error Level. It could be “informational”, “Error”, “Warning”.

Now, Lets see by another way By Raiserror WITH LOG:

It is the same way as we used Raiserror to Raise an Error.

CREATE PROCEDURE TestEventViewer
AS
BEGIN TRY
    SELECT  10/0
END TRY
BEGIN CATCH
    PRINT ERROR_Message()
    DECLARE @msg VARCHAR(100)
    SELECT @msg = ERROR_Message()

    RAISERROR(@msg, 11, 1) WITH LOG

END CATCH

Lets Execute this SP:

EXEC TestEventViewer.

So By these ways we can make an entry to Event Viewer.

Let me know if it helps you in any way

h1

SQL SERVER: How much space occupied by Each Table with sp_MSforeachtable procedure

03/26/2009

Today, I came across requirement where I need to perform an action on all of the tables within a database.

For example, How much space occupied by each table.

I found undocumented Procedure: sp_MSforEachTable in the master database.

The following script reports the space used and allocated for every table in the database.

USE AdventureWorks;
EXECUTE sp_MSforeachtable ‘sp_spaceused [?]’

So, We can use sp_MSforeachtable procedure when we need to loop through each table.

Let me know if it helps you in any way.

Follow

Get every new post delivered to your Inbox.