Archive for the 'SQL Server' Category

19th Aug 2009

How to call procedure from another procedure or Use the data of dynamic sqlserver query in procedure

Today I will explain very small but very useful feature which I have used in the past for the procedures. When I was new to SQL Server I was facing many problems and this was one of them.

We all know user defined functions has limitations that we can not use #temp table or table variables in UDF. Because of that we can not get the data from another function in the UDF.

So to overcome this problem, we can create the procedure in which we get data from another procedure for further manipulation. Question is how to get data from another procedure? You will get the answer of this question in this post.

e.g., suppose procedure ReturnStudentDetail returns the table with two fields “Name” and “City” so how can you get that table in another procedure for further manipulation.

– Create Table

Create table #StudentDetail

(Name varchar (50), City varchar (100))

– Below code will give you data in the procedure

Insert into #StudentDetail

Exec ReturnStudentDetail

This syntax works only if we use create table. You can also use dynamic sqlserver query output for inserting data in #temp table.

– Create Table

Create table #StudentDetail

(Name varchar (50), City varchar (100))

Declare @sql as varchar (500)

Set @sql = ‘Select Name, City from tbl_StudentDetail where ……..’

– Below code will give you data in table

Insert into #StudentDetail

Exec (@sql)

So, this is how you can get the data from another procedure or Dynamic sqlserver query output in Table. Basic thing is whatever the structure of data being returned, you have to create table on basis of that and use that table to get data from procedure or dynamic sqlserver query.

I hope this feature is useful for you in future. Let me know if you find any better way to achieve this.

Posted by Posted by kuldip.bhatt under Filed under SQL Server Comments No Comments »

24th Jul 2009

How to get delimiter separated values in the tabular format in SQL

When ever we write script or code in SQL Server we all face problem like following.

“We store the value in database with the delimiter. Now we want to use that value in the another Procedures or Views and may be to display in reports or any where else in the system. At that time we face problem in getting data out of those delimiter”

So lets see how to get the data in the table format from one column value in which values are stored with some delimiter.

Below is the table value function which gives desired output in the table format.

Parameters which need to be passed in function are:

@String = string value which needs to be formatted for e.g. string like ‘IT,Marketing,Production’. Here as we can see values are separated by comma “,”.

@Delimiter =  Delimiter like coma(,) , Pipe(|)  etc.

Function Code
==========

Create FUNCTION dbo.Split_String(@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (Items nvarchar(4000))
AS
BEGIN

DECLARE @No INT
DECLARE @Item nvarchar(4000)

– Initilize the @no variable with 1
SELECT @No = 1

– if null then return
IF @String IS NULL RETURN
WHILE @No !=0
BEGIN

– get the first o
SELECT @No = CHARINDEX(@Delimiter,@String)

– get the value in the @item variable
IF @No !=0
SELECT @Item = LEFT(@STRING,@No – 1)
ELSE
SELECT @Item = @String

– Put the values in the Result Set
INSERT INTO @Results(Items) VALUES(@Item)

– Remove the item from the main string
SELECT @STRING = RIGHT(@String,LEN(@String) – @No)

– break it work done
IF LEN(@String) = 0 BREAK
END
RETURN

END

Lets check Example of  it:
==============================

Select * from dbo.Split_String(’IT,Marketing,Production’,',’)

Output in table format:
==============================

IT
Marketing
Production

Great! we have all the data in tabular format now which you can easily use anywhere else in your code.

I hope this little function will help you save lot of time and frustration. Please comment if you know any better solution for this.

Posted by Posted by kuldip.bhatt under Filed under Code, SQL Server Comments 1 Comment »

21st Jul 2009

Better way to write dynamic SQL queries

Introduction

When we write Dynamic queries, most of the time only “WHERE” clause needs to be dynamic in the stored procedure rest of the part remains static, I mean “SELECT” and “FROM” Clause remain static most of the time.

To write dynamic query, we are choosing variables so that we can write “WHERE” clause using appropriate conditions and then putting a query in variables. Writing queries like this generates so much confusion while debugging and maintenance of the query.

Here is one of the process by which we can eliminate use of variable while writing queries which provide the same result as a dynamically written query provides.

We can use this technique if the “SELECT” list is going to be static and we need to take care of only “WHERE” clause. Otherwise we can use variables to store SQL query if the columns in the “SELECT” list will be generated dynamically and/or name of the source table will be decided at runtime. To understand this approach let us see one example.

Example

Original Stored Procedure:

We have one stored procedure as below

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

– exec [SC_Report_GetDataByCustomerLounge] 0,1,0,’2009-01-01′,’2009-03-01′

– exec [SC_Report_GetDataByCustomerLounge] 0,0,0,”,”

ALTER PROCEDURE [dbo].[SC_Report_GetDataByCustomerLounge]

@CustomerId int = 0,

@LoungeId int = 0,

@CountryId int = 0,

@FromDate datetime,

@ToDate datetime

AS

DECLARE @StrQuery nvarchar(3000)

DECLARE @WhereCondition nvarchar(3000)

SET @WhereCondition = ”

BEGIN

IF(@CustomerId != 0)

BEGIN

SET @WhereCondition = @WhereCondition + ‘ Trans.CustomerId = ‘ + Convert(varchar,@CustomerId)

END

IF(@LoungeId != 0 AND @WhereCondition != ”)

BEGIN

SET @WhereCondition = @WhereCondition + ‘ AND Trans.LoungeId = ‘ + Convert(varchar,@LoungeId)

END

ELSE IF(@LoungeId != 0)

BEGIN

SET @WhereCondition = @WhereCondition + ‘ Trans.LoungeId = ‘ + Convert(varchar,@LoungeId)

END

IF(@CountryId != 0 AND @WhereCondition != ”)

BEGIN

SET @WhereCondition = @WhereCondition + ‘ AND Trans.CountryId = ‘ + Convert(varchar,@CountryId)

END

ELSE IF(@CountryId != 0)

BEGIN

SET @WhereCondition = @WhereCondition + ‘ Trans.CountryId = ‘ + Convert(varchar,@CountryId)

END

IF (@FromDate != ‘01/01/1900′ AND @ToDate != ‘01/01/1900′ AND @WhereCondition != ”)

BEGIN

SET @WhereCondition = @WhereCondition + ‘ AND Convert(varchar(10),Trans.AccessDate,101) >= ”’ +

Convert(varchar,Convert(varchar(10),@FromDate,101)) + ”’ AND

Convert(varchar(10),Trans.AccessDate,101) <= ”’ +

Convert(varchar,Convert(varchar(10),@ToDate,101)) + ””

END

ELSE IF (@FromDate != ‘01/01/1900′ AND @ToDate != ‘01/01/1900′)

BEGIN

SET @WhereCondition = @WhereCondition + ‘ Convert(varchar(10),Trans.AccessDate,101) >= ”’ +

Convert(varchar,Convert(varchar(10),@FromDate,101)) + ”’ AND Convert(varchar(10),

Trans.AccessDate,101) <= ”’ + Convert(varchar,Convert(varchar(10),@ToDate,101)) + ””

END

IF(@WhereCondition != ”)

BEGIN

Set @StrQuery = ‘Select Trans.TransactionId,Lounge.LoungeId,Cust.CustomerId,

(Cust.FirstName + ” ” + Cust.MiddleName + ” ”+ Cust.LastName ) As CustomerName,

Lounge.LoungeName,City.CityName,Country.CountryName,Cust.Address1,Cust.Address2,

Cust.MobileNo,Cust.EmailAdress,Airport.AirportName,Trans.AccessDate,Trans.Remarks

from dbo.CustomerInformation as Cust

Inner join dbo.TransactionMaster Trans ON Cust.CustomerId = Trans.CustomerId

Inner join dbo.LoungeInformation as Lounge ON Lounge.LoungeId = Trans.LoungeId

Inner join dbo.CityInformation as City ON City.CityId = Trans.CityId

Inner join dbo.CountryInformation as Country ON Country.CountryId = Trans.CountryId

Inner join dbo.AirportInformation as Airport ON Airport.AirportId = Trans.AirportId

WHERE ‘ + @WhereCondition

END

ELSE

BEGIN

Set @StrQuery = ‘Select Trans.TransactionId,Lounge.LoungeId,Cust.CustomerId,

(Cust.FirstName + ” ” + Cust.MiddleName + ” ”+ Cust.LastName ) As CustomerName,

Lounge.LoungeName,City.CityName,Country.CountryName,Cust.Address1,Cust.Address2,

Cust.MobileNo,Cust.EmailAdress,Airport.AirportName,Trans.AccessDate,Trans.Remarks

from dbo.CustomerInformation as Cust

Inner join dbo.TransactionMaster Trans ON Cust.CustomerId = Trans.CustomerId

Inner join dbo.LoungeInformation as Lounge ON Lounge.LoungeId = Trans.LoungeId

Inner join dbo.CityInformation as City ON City.CityId = Trans.CityId

Inner join dbo.CountryInformation as Country ON Country.CountryId = Trans.CountryId

Inner join dbo.AirportInformation as Airport ON Airport.AirportId = Trans.AirportId ‘

END

PRINT @StrQuery

exec sp_executesql @StrQuery

END

From above stored procedure we can see that SELECT query part is static and the query is building dynamically as per change in the WHERE Clause. The above query gives me the following output.

Result before applying alternative approch

Result before applying alternative approch

Alternative way to write same query:

We will be able to replace the above stored procedure using the following stored procedure and that will give same result as previous one.

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

– exec [SC_Report_GetDataByCustomerLounge] 0,1,0,’2009-01-01′,’2009-03-01′

– exec [SC_Report_GetDataByCustomerLounge] 0,0,0,”,”

ALTER PROCEDURE [dbo].[Test]

@CustomerId int = NULL,

@LoungeId int = NULL,

@CountryId int = NULL,

@FromDate datetime = NULL,

@ToDate datetime = NULL

AS

DECLARE @StrQuery nvarchar(3000)

DECLARE @WhereCondition nvarchar(3000)

SET @WhereCondition = ”

BEGIN

Select Trans.TransactionId,Lounge.LoungeId,Cust.CustomerId,

(Cust.FirstName + ‘ ‘ + Cust.MiddleName + ‘ ‘+ Cust.LastName ) As CustomerName,

Lounge.LoungeName,City.CityName,Country.CountryName,Cust.Address1,Cust.Address2,

Cust.MobileNo,Cust.EmailAdress,Airport.AirportName,Trans.AccessDate,Trans.Remarks

from dbo.CustomerInformation as Cust

Inner join dbo.TransactionMaster Trans ON Cust.CustomerId = Trans.CustomerId

Inner join dbo.LoungeInformation as Lounge ON Lounge.LoungeId = Trans.LoungeId

Inner join dbo.CityInformation as City ON City.CityId = Trans.CityId

Inner join dbo.CountryInformation as Country ON Country.CountryId = Trans.CountryId

Inner join dbo.AirportInformation as Airport ON Airport.AirportId = Trans.AirportId

WHERE (Trans.CustomerId = Convert(varchar,@CustomerId) OR Trans.CustomerId = NULL)

AND (Trans.LoungeId = Convert(varchar,@LoungeId) OR Trans.LoungeId = NULL)

AND (Trans.CountryId = Convert(varchar,@CountryId) OR Trans.CountryId = NULL)

AND (Convert(varchar(10),Trans.AccessDate,101) >= Convert(varchar,Convert(varchar(10),@FromDate,101))

AND Convert(varchar(10),Trans.AccessDate,101) <= Convert(varchar,Convert(varchar(10),@ToDate,101)))

END

The above stored procedure gives me the following output:

Result after applying alternative approch

Result after applying alternative approch

The benefits of using this technique are:

  • It will reduce the complexity of query.
  • Using this, we can easily maintain the query.
  • Syntax checking will be much simpler as most of the time quote(‘) gives problem to novice developers when query is stored in a variable.
  • And most important, when we use LINQ –to-SQL in our application structure it will reduce the conversion error between ISingleResult and INT in the case of writing dynamic query.

References:

www.SQLServerCentral.com

Posted by Posted by rakesh.bajania under Filed under SQL Server Comments No Comments »

10th Jul 2009

How to get Data from Dataset into Sqlserver Table by using OPENXML Method?

Some time we need data from Dataset into Sqlserver for insertion or updation in the Sqlserver Tables.

For example if you need to insert an image then you can use this method to insert the data in Sqlserver tables.

Today, I will explain how to get data from Dataset into Sqlserver Table.

– Code for .Net

Dim ds as new Dataset

Dim dt as new Table

dt.TableName = “MyTable”

ds.Tables.add(dt)

Dim lStrWriter As New StringWriter

Dim lStr As String

ds.WriteXML(lStrWriter)

lstr = lStrWriter.Tostring

Pass this lstr variable to the procedure as parameter – @xmldoc.

Now write the code procedure to get the data from Dataset.

— Code in Sqlserver Store Procedure

CREATE PROCEDURE [dbo].[TestXML]

@xmldoc text — Give Text datatype for getting xml from dataset

as

———Read the Datset  From XML —————–

– call sp_xml_preparedocument

DECLARE @idoc int

EXEC sp_xml_preparedocument @idoc OUTPUT, @xmldoc

SELECT * into #TestTable

FROM OPENXML (@idoc, ‘/NewDataSet/MyTable’,2)

WITH (pk_Userid  BigInt,

UserName  Varchar(10))

EXEC sp_xml_removedocument @idoc

———- End Read ———-

END

BY the use of this procedure you get all the data from dataset in to the ”#Testtable” and we can use this as Sqlserver table in procedure.

I hope this article will be useful to you, Please give feedback on this article.

Posted by Posted by kuldip.bhatt under Filed under SQL Server Comments 1 Comment »

05th Jul 2009

SQL SERVER – Difference between Line Feed (\n) and Carriage Return (\r) – T-SQL New Line Char

Today, we will examine something very simple and very generic that can apply to hordes of programming languages. Let’s take a common question that is frequently discussed – What is difference between Line Feed (\n) and Carriage Return (\r)?

Prior to continuing with this article let us first look into few synonyms for LF and CR.

Line Feed – LF – \n – 0×0a – 10 (decimal)

Carriage Return – CR – \r – 0×0D – 13 (decimal)

Now that we have understood that we have two different options to get new line, the question that arises is – why is it so?

The reason is simple. Different operating systems have a different way of understanding new line. Mac only understands ‘\r’ as new line, while Unix and Linux understand ‘\n’ as new line character. Our favorite OS windows needs both the characters together to interpret as new line, which is ‘\r\n’. This is the reason why a file created in one OS does not open properly in another OS and makes it messy.

Now, let us see how we can create a new line in SQL Server. It is a very simple script yet very useful when we have to do run print something or generate scripts. I have illustrated two examples below that are very easy to understand. In the first example, there are no new line chars inserted and for the same, everything is displayed in a single line. However, in the second example, new line char is inserted and the lines are separated with a new line.

Example 1: No new line feed char

DECLARE @NewLineChar AS CHAR(2) = CHAR(13) + CHAR(10)
PRINT ('SELECT FirstLine AS FL SELECT SecondLine AS SL' )
GO


Example 2: With new line feed char

DECLARE @NewLineChar AS CHAR(2) = CHAR(13) + CHAR(10)
PRINT ('SELECT FirstLine AS FL ' +@NewLineChar + 'SELECT SecondLine AS SL' )
GO

I hope my examples make things more clear to you all. Let me have your feedback on this article.

Reference : Pinal Dave (http://blog.SQLAuthority.com)

Posted by Posted by pinaldave under Filed under SQL Server Comments 2 Comments »

04th Jul 2009

Sql Server automatically adjusts nearest 3 milliseconds on Date Selection Criteria

Most of the time we grab the date and time using sql server GetDate() Function.

Sometimes if data is filtered between two dates it may give erroneous result. Why? Because while retrieving data using date as filter criteria, it will fetch records which are nearest 3 milliseconds.

It will be more clear by following example.

Create Table datetesting
(
PK_id INT IDENTITY,
Datefield DateTime
)

Insert into datetesting(DateField)
Values (’1/2/09 00:00′)
Insert into datetesting(DateField)
Values (’1/2/09 23:59′)

Insert into datetesting(DateField)
Values (’1/2/09 11:59:59.995 pm’)

Insert into datetesting(DateField)
Values (’1/3/09′)

Now Execute the following query

Select * from datetesting where Datefield Between ‘1/2/9′ AND ‘1/2/9 11:59:59.998 PM’

Result of the above query

PK_id        DateField
—————————————
1        2009-01-02 00:00:00.000
2        2009-01-02 23:59:00.000
3        2009-01-02 23:59:59.997

Now, Try the following query to retrieve data. I have just added 1 millisecond and it will retrieve date 2009-01-03 00:00:00.000 which does not match the criteria.

Select * from datetesting where Datefield Between ‘1/2/9′ AND ‘1/2/9 11:59:59.999 PM’

PK_id        DateField
—————————————
1    2009-01-02 00:00:00.000
2    2009-01-02 23:59:00.000
3    2009-01-02 23:59:59.997
4    2009-01-03 00:00:00.000

So next time when you face wrong data by filter, don’t get perplexed, This may be the reason!

Posted by Posted by kalpesh.patel under Filed under SQL Server Comments 3 Comments »

22nd Jun 2009

How to Convert Cursor into While Loop In Sqlserver ?

I personally face this issues in many Store Procedures i.e. Cursor taking too much time to execute. I am sure many of you will be having similar problem.

I have worked on that issue and found following solution. It may not be perfect for cursor optimization but it does work in my case.

– Original Cursor Code —

Declare @fk_MedicationOrderId as Bigint
Declare @AdminTime as Bigint

declare CUR_MEDICATIONORDERID cursor FOR
select
fk_MedicationOrderId
from
tbl_medicationorderDetail_trn
where
Actiondate > Getdate()

OPEN CUR_MEDICATIONORDERID

FETCH NEXT FROM CUR_MEDICATIONORDERID
INTO @fk_MedicationOrderId

WHILE @@FETCH_STATUS =0
BEGIN

Select @AdminTime=AdminTime from tbl_medicationorderDetail_trn
where fk_medicationorderid = @fk_MedicationOrderId

Update tbl_TempMedicationOrderDetail_trn
set ActionTime = @AdminTime
set @AdminTime = ”

FETCH NEXT FROM CUR_MEDICATIONORDERID
INTO @fk_MedicationOrderId

END

CLOSE CUR_MEDICATIONORDERID
DEALLOCATE CUR_MEDICATIONORDERID

——————-

– Modified Cursor Code (faster) –

Declare @fk_MedicationOrderId as Bigint
Declare @AdminTime as Bigint

Declare Table for the fields you need in the cursor.

declare @IDList table (ID Bigint)

Insert into @IDList
select
fk_MedicationOrderId
from
tbl_medicationorderDetail_trn
where
Actiondate > Getdate()

while (select count(ID) from @IDList) > 0
begin
select top 1 @fk_MedicationOrderId = ID from @IDList

Select @AdminTime=AdminTime from tbl_medicationorderDetail_trn
where fk_medicationorderid = @fk_MedicationOrderId

Update tbl_TempMedicationOrderDetail_trn
set ActionTime = @AdminTime
set @AdminTime = ”

delete from @IDList where ID = @fk_MedicationOrderId

end

——————-

What I have done here is to convert “cursor” into “while loop”. It is just to get your data in any temporary table or table variable after that just delete the rows from that at end of loop.

It helps in improving performance, I have personally tried it in many stored procedures.

Let me know if you find any other useful way of improving performance.

Posted by Posted by kuldip.bhatt under Filed under SQL Server Comments 9 Comments »

15th Jun 2009

CLR Stored Procedures and creating it step by step

Download code & SQL statements: BlueDownArrow

Introduction:

We usually face problem in Stored Procedures and other database object when we need to implement some complicated logic within it. We found inefficient performance when we try to implement complex logic & business rules in database objects. In many cases we found C# or VB classes more powerful to implement such things. Microsoft has launched a new concept to resolve such issues with SQL server 2005 called “CLR Stored Procedure”.

What is CLR Stored Procedure?

Now, let us understand CLR stored procedure. CLR as most of .Net programmer knows is Common Language Runtime and Stored Procedures are routine stored procedures of database. Thus, CLR Stored Procedures are combination of both. As we all know, Common Language Runtime is core .Net component. The Common Language Runtime is runtime execution environment which supplies managed code with various services like cross language integration, code access security, lifetime management of object, resources management, threading, debugging & type safety etc. So now, CLR Stored Procedures are .Net objects which run in the memory of database.

The very first usage of CLR Stored Procedures can be said accessing system resources. Accessing system resources could also be done using Extended Stored Procedures which are again database object like Stored Procedures, Functions etc. Extended Stored Procedures can do most of the things which a standard executable program can do. Then, why are CLR Stored Procedures? The very first advantage of CLR Stored Procedures is it is a managed object unlike Extended Stored Procedures, which are unmanaged objects. The common thing between them is both runs under database memory. In this way CLR Stored Procedures gives all the benefits of managed objects. Following screen explains memory allocation while execution of CLR Stored Procedure.

0

When should I use CLR Stored Procedure?

Extended stored procedures run in the same process space as the database engine, memory leaks, bugs etc., can affects the performance of database engine. CLR stored procedures resolves these issues as they are managed object and runs per specifications of Common Language Runtime. CLR Stored Procedures can replace a standard stored procedure that contains complex logic and business rules. CLR Stored Procedures takes benefit of .Net classes and thus makes easy to implement complex logic, calculation, intense string operations, complex iterations, data encryptions etc., that are difficult to obtain in standard stored procedures. Standard stored procedures are still best for data oriented tasks. CLR Stored Procedures not only includes stored procedures but also includes Functions, Triggers etc. CLR Stored Procedures are compiled one so gives better performance.

Benefits of CLR Stored Procedures:

  1. Gives better results while executing complex logic, intense string operation or string manipulations, cryptography, accessing system resources and file management etc.
  2. CLR Stored Procedures are managed codes so ensures type safety, memory management etc.
  3. Better code management and provides object oriented programming capability thus enables encapsulation, polymorphism & inheritance.
  4. Convenient for programmer as CLR Stored Procedures can be written in C#, VB or any other language that .Net Framework supports.
  5. CLR Stored Procedures can also be used with Oracle 10g Release 2 or later versions.
  6. Not convenient in all contexts for e.g. it should not be used to execute simple queries. In that case standard stored procedures give better results.
  7. Deployment may be difficult in some scenarios.

Drawbacks of CLR Stored Procedures:

  1. Not convenient in all contexts for e.g. it should not be used to execute simple queries. In that case standard stored procedures give better results.
  2. Deployment may be difficult in some scenarios.

Standard Stored Procedures vs. CLR Stored Procedures:

You are the best judge when to use regular Stored Procedures and when to use CLR Stored Procedures. CLR Stored Procedures can be used in following scenarios.

  1. When the program requires complex logic or business rules.
  2. When the flow is CPU intensive. CLR Stored Procedures gives better results as they are in complied form and managed one.
  3. The tasks which are not possible in TSQL, accessing system resources, cryptography, accessing web services etc.
  4. In option of Extended Stored Procedures. One should always consider CLR Stored Procedures before going for Extended Stored Procedures.
  5. An operation requires higher data safety.

Creating CLR Stored Procedure step by step:

Let us create one simple CLR Stored Procedure which fetches all the rows from one table of the database. I have attached whole list of SQL statement used for creating database, creating table, inserting dummy records in the table etc., under “SQL statements used in the demo” section.

Application development specification:

  • IDE: Visual Studio 2008
  • Framework: 3.5 with SP 1
  • Language: C# 3.0
  • Database MS SQL Server 2005 Express edition

Steps to create CLR Stored Procedure:

1) Open Microsoft Visual Studio >> Click on New Project >> Select Database Projects >> SQL Server Project.

1

2) You can choose reference of existing database connection or click on Add New Reference.

2

3) If you selects from existing references skit step 3 else add new database reference as shown in following image and click on Test Connection to test the connection.

3

4) On clicking on OK button, Visual Studio will ask you to enable SQL/CLR debugging on the selected connection. You can select “Yes” to enable debugging or “No” to disable the same.

4

5) Once the database reference and debugging option is selected, the project will be displayed in Solution Explorer. Select the project and right click on Solution Explorer >> Click on Add >> Stored Procedure.

5

6) Add new procedure from the installed templates as shown in following screen. Give proper name to it.

6

7) Once you select the template, it will create .cs file with the content shown in following image.

7

8 ) Add following code in the method already created. Pass “context connection=true” as connection string in the constructor while creating new SqlConnection. This CLR stored procedure is going to be the part of the database, so it will be the internal part of database so no need to connect database externally. So, no need to provide connection string that we usually provide in applications. Then Click on Build menu >> Click on Build Solution. Also click on Build menu >> Deploy solution. This will deploy the assembly to the database for which we have made connection initially.

8

9) Now, select the database >> Programmability. Right click on Stored Procedures >> Click on Refresh. The list of Stored Procedures should show one newly added stored procedure. Also right click on Assemblies >> click on Refresh. This should show newly added Assembly. Also, enable CLR Stored Procedure by following query.

sp_configure ‘clr enabled’, 1

Run following query to take effect or above query.

RECONFIGURE

Now, execute the stored procedure. It should give similar results shown in following screen.

9

SQL statements used in the demo:

Following is the queries to create database, create table, insert records in the table etc.

–Create a new databse for demo

CREATE DATABASE DbForClrDemo

–Use database

USE DbForClrDemo

–Create table for CustomerSalesInformation

CREATE TABLE [dbo].[CustomerSalesInformation](

[Id] [int] IDENTITY(1,1) NOT NULL,

[Name] [varchar](50) NOT NULL,

[Sales] [decimal](18, 2) NOT NULL DEFAULT ((0)),

CONSTRAINT [PK_CustomerSalesInformation] PRIMARY KEY CLUSTERED

(

[Id] ASC

)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

–Insert dummy data to CustomerSalesInformation table

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (’Virat Kothari’, 50000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (’Dhruval Shah’, 5000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (’Urvish Sheth’, 15000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (’Rakesh Bajania’, 25000)

INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (’Dhaval Shah’, 150000)

–Enable CLR Stored Procedure in database

sp_configure ‘clr enabled’, 1

–Run following statuement to take effect of above statement

RECONFIGURE

–Now execute our CLR Stored Procedure. Remember “ClrDemo” is name of our Stored Procedure

EXEC [dbo].ClrDemo

Conclusion:

CLR Stored procedures are very simple and can be used in most complex scenarios.

Bibliography:

  1. MSDN (http://msdn.microsoft.com/en-us/library/ms131094.aspx)
  2. Code project
  3. http://searchsqlserver.techtarget.com/generic/0,295582,sid87_gci1251402,00.html

Reference : Virat Kothari (www.viratkothari.wordpress.com)

Posted by Posted by virat.kothari under Filed under SQL Server Comments 4 Comments »

12th Jun 2009

SQL SERVER – sqlcmd – Using a Dedicated Administrator Connection to Kill Currently Running Query

People are judged from their questions and not their answers. I received wonderful question the other day.

How sqlcmd can be used along with currently running query script posted on your blog?

Please read following two posts before continuing this article as they cover background of this article.

SQL SERVER – Interesting Observation – Using sqlcmd From SSMS Query Editor

SQL SERVER – Find Currently Running Query – T-SQL

If due to long running query or any resource hogging query SQL Server is not responding sqlcmd can be used to connect to server from another computer and kill the offending query. SQL Server provides a special diagnostic connection which allows administrators to access SQL Server when standard connection is no tpossible. Except very extreme situations dedicated administrator connection (DAC) is always successfull.

Let us see how we can use DAC using sqlcmd.

Connect SQL Server using sqlcmd and -A option which will establish DAC.

C:\>sqlcmd -S localhost -U sa -P dev -d master -A

For our test purpose run following query which overload server and probably make it unresponsive. If your configure is not strong I strongly suggest not to run following query.

Following query is just for test purpose and not part of solution.

USE AdventureWorks
GO
SELECT *
FROM Person.Address
CROSS JOIN Person.Address a1
CROSS JOIN Person.Address a2
CROSS JOIN Person.Address a3
CROSS JOIN Person.Address a4
CROSS JOIN Person.Address a5
CROSS JOIN Person.Address a6
CROSS JOIN Person.Address a7
CROSS JOIN Person.Address a8
CROSS JOIN Person.Address a9
GO

Once successfully connected it will provide prompt 1> enter following T-SQL query which will give SessionID of currently running query along with its elapsed time.

SELECT
req.session_id,
req.status,
req.total_elapsed_time
FROM sys.dm_exec_requests req
WHERE status = 'running'
AND req.total_elapsed_time > 1

Our previously running query gave session id 52 in on my server. The session id may be different for each SQL Server. Once the session id is figured out it can be killed using KILL [SessionID] command. Always make sure to type command GO after each complete query.

KILL 52

Once above query has run it will kill our example long running query and give following error.

Msg 233, Level 20, State 0, Line 0

A transport-level error has occurred when receiving results from the server. (provider: Shared Memory Provider, error: 0 – No process is on the other end of the pipe.)

sqlcmd is really useful utility of SQL Server and it comes in handy when server is not responsive. I strongly suggest to bookmark this article as it can come to rescue when nothing works and SQL Server is unresponsive.

Reference : Pinal Dave (http://blog.SQLAuthority.com)

Posted by Posted by pinaldave under Filed under SQL Server Comments 1 Comment »

05th Jun 2009

How to Find and Replace in Update Query?

How to Find and Replace in Update Query ?

For e.g. I have field name orderFreQuencyvalues in tbl_OrderFrequency_mst

This Field contains values like ‘04:30,05:00,05:30,06:00′ i.e coma separated values in one field of a table.

Now, how do I replace ‘06:00′ with ‘06:30′ in a query ? Let do it here.

Declare the Variables.

DECLARE  @find      varchar(255),
@replace   varchar(255),
@patfind   varchar(255)

Initialize the values for the variables.

SELECT   @find    = ‘06:00′,
@replace = ‘06:30′

SELECT   @patfind = ‘%’ + @find + ‘%’

Run the below query.

UPDATE   tbl_OrderFrequency_mst
SET      orderFreQuencyvalues = STUFF( orderFreQuencyvalues,
PATINDEX( @patfind, orderFreQuencyvalues ),
DATALENGTH( @find ),
@replace )

WHERE    orderFreQuencyvalues LIKE @patfind

STUFF( text or Field Name , start , length , Replace value)

Purpose of STUFF:
Deletes a specified length of characters and inserts another set of characters at a specified starting point

Patindex( FindValue , text or Field Name)
Find the Index where Findvalue Start

Datalength( TextData )
Return the lenght of the text

I hope you find this useful somewhere.

Posted by Posted by kuldip.bhatt under Filed under SQL Server Comments No Comments »