<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Digicorp &#187; SQL Server</title>
	<atom:link href="http://dev.digi-corp.com/category/sql-server/feed/" rel="self" type="application/rss+xml" />
	<link>http://dev.digi-corp.com</link>
	<description>&#62;&#62; Developer Blog</description>
	<lastBuildDate>Wed, 22 Jun 2011 14:13:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>How to call procedure from another procedure or Use the data of dynamic sqlserver query in procedure</title>
		<link>http://dev.digi-corp.com/2009/08/how-to-call-procedure-from-another-procedure-or-use-the-data-of-dynamic-sqlserver-query-in-procedure/</link>
		<comments>http://dev.digi-corp.com/2009/08/how-to-call-procedure-from-another-procedure-or-use-the-data-of-dynamic-sqlserver-query-in-procedure/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 05:55:55 +0000</pubDate>
		<dc:creator>kuldip.bhatt</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Data from Procedure]]></category>
		<category><![CDATA[dynamic query]]></category>
		<category><![CDATA[Procedure]]></category>
		<category><![CDATA[Sqlserver]]></category>
		<category><![CDATA[stored procedure]]></category>

		<guid isPermaLink="false">http://dev.digi-corp.com/?p=1227</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>e.g., suppose procedure <strong>ReturnStudentDetail</strong> returns the table with two fields <em>&#8220;Name&#8221;</em> and <em>&#8220;City&#8221;</em> so how can you get that table in another procedure for further manipulation.</p>
<p>&#8211; Create Table</p>
<p style="padding-left: 30px;"><strong>Create table #StudentDetail</strong></p>
<p style="padding-left: 30px;"><strong>(Name varchar (50), City varchar (100))</strong></p>
<p>&#8211; Below code will give you data in the procedure</p>
<p style="padding-left: 30px;"><strong>Insert into #StudentDetail</strong></p>
<p style="padding-left: 30px;"><strong>Exec ReturnStudentDetail</strong></p>
<p><strong> </strong></p>
<p>This syntax works only if we use create table. You can also use dynamic sqlserver query output for inserting data in #temp table.</p>
<p><strong> </strong></p>
<p style="padding-left: 30px;">&#8211; Create Table</p>
<p style="padding-left: 30px;"><strong>Create table #StudentDetail</strong></p>
<p style="padding-left: 30px;"><strong>(Name varchar (50), City varchar (100))</strong></p>
<p style="padding-left: 30px;"><strong> </strong></p>
<p style="padding-left: 30px;"><strong>Declare @sql as varchar (500)</strong></p>
<p style="padding-left: 30px;"><strong> </strong></p>
<p style="padding-left: 30px;"><strong>Set @sql = ‘Select Name, City from tbl_StudentDetail where ……..’</strong></p>
<p><strong> </strong></p>
<p>&#8211; Below code will give you data in table</p>
<p style="padding-left: 30px;"><strong>Insert into #StudentDetail</strong></p>
<p style="padding-left: 30px;"><strong>Exec (@sql)</strong></p>
<p>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.</p>
<p>I hope this feature is useful for you in future. Let me know if you find any better way to achieve this.</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.digi-corp.com/2009/08/how-to-call-procedure-from-another-procedure-or-use-the-data-of-dynamic-sqlserver-query-in-procedure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to get delimiter separated values in the tabular format in SQL</title>
		<link>http://dev.digi-corp.com/2009/07/how-to-get-delimiter-separated-values-in-the-tabular-format-in-sql/</link>
		<comments>http://dev.digi-corp.com/2009/07/how-to-get-delimiter-separated-values-in-the-tabular-format-in-sql/#comments</comments>
		<pubDate>Fri, 24 Jul 2009 12:14:18 +0000</pubDate>
		<dc:creator>kuldip.bhatt</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Column to Row]]></category>
		<category><![CDATA[Coma seprated]]></category>
		<category><![CDATA[Delimited values]]></category>
		<category><![CDATA[Delimiter Seprated]]></category>
		<category><![CDATA[Sqlserver]]></category>

		<guid isPermaLink="false">http://dev.digi-corp.com/?p=1173</guid>
		<description><![CDATA[When ever we write script or code in SQL Server we all face problem like following. &#8220;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 [...]]]></description>
			<content:encoded><![CDATA[<p>When ever we write script or code in SQL Server we all face problem like following.</p>
<p><em>&#8220;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&#8221;</em></p>
<p>So lets see how to get the data in the table format from one column value in which values are stored with some delimiter.</p>
<p>Below is the table value function which gives desired output in the table format.</p>
<p>Parameters which need to be passed in function are:</p>
<p><em>@String = string value which needs to be formatted </em>for e.g. string like <em>&#8216;IT,Marketing,Production&#8217;</em>. Here as we can see values are separated by comma &#8220;,&#8221;.</p>
<p>@Delimiter =  Delimiter like coma(,) , Pipe(|)  etc.</p>
<p>Function Code<br />
==========</p>
<p style="padding-left: 30px;">Create FUNCTION dbo.Split_String(@String nvarchar(4000), @Delimiter char(1))<br />
RETURNS @Results TABLE (Items nvarchar(4000))<br />
AS<br />
BEGIN</p>
<p style="padding-left: 30px;">DECLARE @No INT<br />
DECLARE @Item nvarchar(4000)</p>
<p style="padding-left: 30px;">&#8211; Initilize the @no variable with 1<br />
SELECT @No = 1</p>
<p style="padding-left: 30px;">&#8211; if null then return<br />
IF @String IS NULL RETURN<br />
WHILE @No !=0<br />
BEGIN</p>
<p style="padding-left: 30px;">&#8211; get the first o<br />
SELECT @No = CHARINDEX(@Delimiter,@String)</p>
<p style="padding-left: 30px;">&#8211; get the value in the @item variable<br />
IF @No !=0<br />
SELECT @Item = LEFT(@STRING,@No &#8211; 1)<br />
ELSE<br />
SELECT @Item = @String</p>
<p style="padding-left: 30px;">&#8211; Put the values in the Result Set<br />
INSERT INTO @Results(Items) VALUES(@Item)</p>
<p style="padding-left: 30px;">&#8211; Remove the item from the main string<br />
SELECT @STRING = RIGHT(@String,LEN(@String) &#8211; @No)</p>
<p style="padding-left: 30px;">&#8211; break it work done<br />
IF LEN(@String) = 0 BREAK<br />
END<br />
RETURN</p>
<p style="padding-left: 30px;">END</p>
<p>Lets check Example of  it:<br />
==============================</p>
<p style="padding-left: 30px;"><em>Select * from dbo.Split_String(&#8216;IT,Marketing,Production&#8217;,',&#8217;)</em></p>
<p>Output in table format:<br />
==============================</p>
<p style="padding-left: 30px;">IT<br />
Marketing<br />
Production</p>
<p>Great! we have all the data in tabular format now which you can easily use anywhere else in your code.</p>
<p>I hope this little function will help you save lot of time and frustration. Please comment if you know any better solution for this.</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.digi-corp.com/2009/07/how-to-get-delimiter-separated-values-in-the-tabular-format-in-sql/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Better way to write dynamic SQL queries</title>
		<link>http://dev.digi-corp.com/2009/07/better-way-to-write-dynamic-sql-queries/</link>
		<comments>http://dev.digi-corp.com/2009/07/better-way-to-write-dynamic-sql-queries/#comments</comments>
		<pubDate>Tue, 21 Jul 2009 12:53:43 +0000</pubDate>
		<dc:creator>rakesh.bajania</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[dynamic query]]></category>
		<category><![CDATA[dynamic rakesh]]></category>
		<category><![CDATA[rakesh]]></category>
		<category><![CDATA[rakesh bajania]]></category>
		<category><![CDATA[rakesh dynamic]]></category>
		<category><![CDATA[sql dynamic query]]></category>

		<guid isPermaLink="false">http://dev.digi-corp.com/?p=935</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<h2>Example</h2>
<h3>Original Stored Procedure:</h3>
<p>We have one stored procedure as below</p>
<p>set ANSI_NULLS ON</p>
<p>set QUOTED_IDENTIFIER ON</p>
<p>GO</p>
<p>&#8211; exec [SC_Report_GetDataByCustomerLounge] 0,1,0,&#8217;2009-01-01&#8242;,&#8217;2009-03-01&#8242;</p>
<p>&#8211; exec [SC_Report_GetDataByCustomerLounge] 0,0,0,&#8221;,&#8221;</p>
<p>ALTER PROCEDURE [dbo].[SC_Report_GetDataByCustomerLounge]</p>
<p>@CustomerId int = 0,</p>
<p>@LoungeId int = 0,</p>
<p>@CountryId int = 0,</p>
<p>@FromDate datetime,</p>
<p>@ToDate datetime</p>
<p>AS</p>
<p>DECLARE @StrQuery nvarchar(3000)</p>
<p>DECLARE @WhereCondition nvarchar(3000)</p>
<p>SET @WhereCondition = &#8221;</p>
<p>BEGIN</p>
<p>IF(@CustomerId != 0)</p>
<p>BEGIN</p>
<p>SET @WhereCondition = @WhereCondition + &#8216; Trans.CustomerId = &#8216; + Convert(varchar,@CustomerId)</p>
<p>END</p>
<p>IF(@LoungeId != 0 AND @WhereCondition != &#8221;)</p>
<p>BEGIN</p>
<p>SET @WhereCondition = @WhereCondition + &#8216; AND Trans.LoungeId = &#8216; + Convert(varchar,@LoungeId)</p>
<p>END</p>
<p>ELSE IF(@LoungeId != 0)</p>
<p>BEGIN</p>
<p>SET @WhereCondition = @WhereCondition + &#8216; Trans.LoungeId = &#8216; + Convert(varchar,@LoungeId)</p>
<p>END</p>
<p>IF(@CountryId != 0 AND @WhereCondition != &#8221;)</p>
<p>BEGIN</p>
<p>SET @WhereCondition = @WhereCondition + &#8216; AND Trans.CountryId = &#8216; + Convert(varchar,@CountryId)</p>
<p>END</p>
<p>ELSE IF(@CountryId != 0)</p>
<p>BEGIN</p>
<p>SET @WhereCondition = @WhereCondition + &#8216; Trans.CountryId = &#8216; + Convert(varchar,@CountryId)</p>
<p>END</p>
<p>IF (@FromDate != &#8217;01/01/1900&#8242; AND @ToDate != &#8217;01/01/1900&#8242; AND @WhereCondition != &#8221;)</p>
<p>BEGIN</p>
<p>SET @WhereCondition = @WhereCondition + &#8216; AND Convert(varchar(10),Trans.AccessDate,101) &gt;= &#8221;&#8217; +</p>
<p>Convert(varchar,Convert(varchar(10),@FromDate,101)) + &#8221;&#8217; AND</p>
<p>Convert(varchar(10),Trans.AccessDate,101) &lt;= &#8221;&#8217; +</p>
<p>Convert(varchar,Convert(varchar(10),@ToDate,101)) + &#8221;&#8221;</p>
<p>END</p>
<p>ELSE IF (@FromDate != &#8217;01/01/1900&#8242; AND @ToDate != &#8217;01/01/1900&#8242;)</p>
<p>BEGIN</p>
<p>SET @WhereCondition = @WhereCondition + &#8216; Convert(varchar(10),Trans.AccessDate,101) &gt;= &#8221;&#8217; +</p>
<p>Convert(varchar,Convert(varchar(10),@FromDate,101)) + &#8221;&#8217; AND Convert(varchar(10),</p>
<p>Trans.AccessDate,101) &lt;= &#8221;&#8217; + Convert(varchar,Convert(varchar(10),@ToDate,101)) + &#8221;&#8221;</p>
<p>END</p>
<p>IF(@WhereCondition != &#8221;)</p>
<p>BEGIN</p>
<p>Set @StrQuery = &#8216;Select Trans.TransactionId,Lounge.LoungeId,Cust.CustomerId,</p>
<p>(Cust.FirstName + &#8221; &#8221; + Cust.MiddleName + &#8221; &#8221;+ Cust.LastName ) As CustomerName,</p>
<p>Lounge.LoungeName,City.CityName,Country.CountryName,Cust.Address1,Cust.Address2,</p>
<p>Cust.MobileNo,Cust.EmailAdress,Airport.AirportName,Trans.AccessDate,Trans.Remarks</p>
<p>from dbo.CustomerInformation as Cust</p>
<p>Inner join dbo.TransactionMaster Trans ON Cust.CustomerId = Trans.CustomerId</p>
<p>Inner join dbo.LoungeInformation as Lounge ON Lounge.LoungeId = Trans.LoungeId</p>
<p>Inner join dbo.CityInformation as City ON City.CityId = Trans.CityId</p>
<p>Inner join dbo.CountryInformation as Country ON Country.CountryId = Trans.CountryId</p>
<p>Inner join dbo.AirportInformation as Airport ON Airport.AirportId = Trans.AirportId</p>
<p>WHERE &#8216; + @WhereCondition</p>
<p>END</p>
<p>ELSE</p>
<p>BEGIN</p>
<p>Set @StrQuery = &#8216;Select Trans.TransactionId,Lounge.LoungeId,Cust.CustomerId,</p>
<p>(Cust.FirstName + &#8221; &#8221; + Cust.MiddleName + &#8221; &#8221;+ Cust.LastName ) As CustomerName,</p>
<p>Lounge.LoungeName,City.CityName,Country.CountryName,Cust.Address1,Cust.Address2,</p>
<p>Cust.MobileNo,Cust.EmailAdress,Airport.AirportName,Trans.AccessDate,Trans.Remarks</p>
<p>from dbo.CustomerInformation as Cust</p>
<p>Inner join dbo.TransactionMaster Trans ON Cust.CustomerId = Trans.CustomerId</p>
<p>Inner join dbo.LoungeInformation as Lounge ON Lounge.LoungeId = Trans.LoungeId</p>
<p>Inner join dbo.CityInformation as City ON City.CityId = Trans.CityId</p>
<p>Inner join dbo.CountryInformation as Country ON Country.CountryId = Trans.CountryId</p>
<p>Inner join dbo.AirportInformation as Airport ON Airport.AirportId = Trans.AirportId &#8216;</p>
<p>END</p>
<p>PRINT @StrQuery</p>
<p>exec sp_executesql @StrQuery</p>
<p>END</p>
<p>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.</p>
<div id="attachment_934" class="wp-caption alignnone" style="width: 1034px"><a href="http://dev.digi-corp.com/wp-content/uploads/2009/07/1.PNG"><img class="size-full wp-image-934" src="http://dev.digi-corp.com/wp-content/uploads/2009/07/1.PNG" alt="Result before applying alternative approch" width="1024" height="768" /></a><p class="wp-caption-text">Result before applying alternative approch</p></div>
<h3>Alternative way to write same query:</h3>
<p>We will be able to replace the above stored procedure using the following stored procedure and that will give same result as previous one.</p>
<p>set ANSI_NULLS ON</p>
<p>set QUOTED_IDENTIFIER ON</p>
<p>GO</p>
<p>&#8211; exec [SC_Report_GetDataByCustomerLounge] 0,1,0,&#8217;2009-01-01&#8242;,&#8217;2009-03-01&#8242;</p>
<p>&#8211; exec [SC_Report_GetDataByCustomerLounge] 0,0,0,&#8221;,&#8221;</p>
<p>ALTER PROCEDURE [dbo].[Test]</p>
<p>@CustomerId int = NULL,</p>
<p>@LoungeId int = NULL,</p>
<p>@CountryId int = NULL,</p>
<p>@FromDate datetime = NULL,</p>
<p>@ToDate datetime = NULL</p>
<p>AS</p>
<p>DECLARE @StrQuery nvarchar(3000)</p>
<p>DECLARE @WhereCondition nvarchar(3000)</p>
<p>SET @WhereCondition = &#8221;</p>
<p>BEGIN</p>
<p>Select Trans.TransactionId,Lounge.LoungeId,Cust.CustomerId,</p>
<p>(Cust.FirstName + &#8216; &#8216; + Cust.MiddleName + &#8216; &#8216;+ Cust.LastName ) As CustomerName,</p>
<p>Lounge.LoungeName,City.CityName,Country.CountryName,Cust.Address1,Cust.Address2,</p>
<p>Cust.MobileNo,Cust.EmailAdress,Airport.AirportName,Trans.AccessDate,Trans.Remarks</p>
<p>from dbo.CustomerInformation as Cust</p>
<p>Inner join dbo.TransactionMaster Trans ON Cust.CustomerId = Trans.CustomerId</p>
<p>Inner join dbo.LoungeInformation as Lounge ON Lounge.LoungeId = Trans.LoungeId</p>
<p>Inner join dbo.CityInformation as City ON City.CityId = Trans.CityId</p>
<p>Inner join dbo.CountryInformation as Country ON Country.CountryId = Trans.CountryId</p>
<p>Inner join dbo.AirportInformation as Airport ON Airport.AirportId = Trans.AirportId</p>
<p>WHERE (Trans.CustomerId = Convert(varchar,@CustomerId) OR Trans.CustomerId = NULL)</p>
<p>AND (Trans.LoungeId = Convert(varchar,@LoungeId) OR Trans.LoungeId = NULL)</p>
<p>AND (Trans.CountryId = Convert(varchar,@CountryId) OR Trans.CountryId = NULL)</p>
<p>AND (Convert(varchar(10),Trans.AccessDate,101) &gt;= Convert(varchar,Convert(varchar(10),@FromDate,101))</p>
<p>AND Convert(varchar(10),Trans.AccessDate,101) &lt;= Convert(varchar,Convert(varchar(10),@ToDate,101)))</p>
<p>END</p>
<p>The above stored procedure gives me the following output:</p>
<div id="attachment_933" class="wp-caption alignnone" style="width: 1034px"><a href="http://dev.digi-corp.com/wp-content/uploads/2009/07/2.PNG"><img class="size-full wp-image-933" src="http://dev.digi-corp.com/wp-content/uploads/2009/07/2.PNG" alt="Result after applying alternative approch" width="1024" height="768" /></a><p class="wp-caption-text">Result after applying alternative approch</p></div>
<p><strong>The benefits of using this technique are:</strong></p>
<ul>
<li>It will reduce the complexity of query.</li>
<li>Using this, we can easily maintain the query.</li>
<li>Syntax checking will be much simpler as most of the time quote(‘) gives problem to novice developers when query is stored in a variable.</li>
<li>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.</li>
</ul>
<p><strong>References:</strong></p>
<p>www.SQLServerCentral.com</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.digi-corp.com/2009/07/better-way-to-write-dynamic-sql-queries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to get Data from Dataset into Sqlserver Table by using OPENXML Method?</title>
		<link>http://dev.digi-corp.com/2009/07/how-to-get-data-from-dataset-into-sqlserver-table-by-using-openxml-method/</link>
		<comments>http://dev.digi-corp.com/2009/07/how-to-get-data-from-dataset-into-sqlserver-table-by-using-openxml-method/#comments</comments>
		<pubDate>Sat, 11 Jul 2009 06:36:41 +0000</pubDate>
		<dc:creator>kuldip.bhatt</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Openxml]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Xml]]></category>
		<category><![CDATA[XML to Sql]]></category>
		<category><![CDATA[XMLRead]]></category>

		<guid isPermaLink="false">http://dev.digi-corp.com/?p=878</guid>
		<description><![CDATA[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. &#8211; Code for [...]]]></description>
			<content:encoded><![CDATA[<p>Some time we need data from Dataset into Sqlserver for insertion or updation in the Sqlserver Tables.</p>
<p>For example if you need to insert an image then you can use this method to insert the data in Sqlserver tables.</p>
<p>Today, I will explain how to get data from Dataset into Sqlserver Table.</p>
<p><strong>&#8211; Code for .Net</strong></p>
<p><em>Dim ds as new Dataset</em></p>
<p><em>Dim dt as new Table</em></p>
<p><em>dt.TableName = &#8220;MyTable&#8221;</em></p>
<p><em>ds.Tables.add(dt)</em></p>
<p><em>Dim lStrWriter As New StringWriter</em></p>
<p><em>Dim lStr As String</em></p>
<p><em>ds.WriteXML(lStrWriter)</em></p>
<p><em>lstr = lStrWriter.Tostring</em></p>
<p>Pass this lstr variable to the procedure as parameter &#8211; @xmldoc.</p>
<p>Now write the code procedure to get the data from Dataset.</p>
<p><strong> &#8212; Code in Sqlserver Store Procedure</strong></p>
<p><em>CREATE PROCEDURE [dbo].[TestXML]</em></p>
<p><em>@xmldoc text &#8212; Give Text datatype for getting xml from dataset</em></p>
<p><em>as</em></p>
<p><em>&#8212;&#8212;&#8212;Read the Datset  From XML &#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</em></p>
<p><em>&#8211; call sp_xml_preparedocument</em></p>
<p><em>DECLARE @idoc int</em></p>
<p><em>EXEC sp_xml_preparedocument @idoc OUTPUT, @xmldoc</em></p>
<p><em>SELECT * into #TestTable</em></p>
<p><em>FROM OPENXML (@idoc, &#8216;/NewDataSet/MyTable&#8217;,2)</em></p>
<p><em>WITH (pk_Userid  BigInt,</em></p>
<p><em>UserName  Varchar(10))</em></p>
<p><em>EXEC sp_xml_removedocument @idoc</em></p>
<p><em>&#8212;&#8212;&#8212;- End Read &#8212;&#8212;&#8212;-</em></p>
<p><em>END</em></p>
<p>BY the use of this procedure you get all the data from dataset in to the &#8221;#Testtable&#8221; and we can use this as Sqlserver table in procedure.</p>
<p>I hope this article will be useful to you, Please give feedback on this article.</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.digi-corp.com/2009/07/how-to-get-data-from-dataset-into-sqlserver-table-by-using-openxml-method/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>SQL SERVER – Difference between Line Feed (\n) and Carriage Return (\r) – T-SQL New Line Char</title>
		<link>http://dev.digi-corp.com/2009/07/sql-server-%e2%80%93-difference-between-line-feed-n-and-carriage-return-r-%e2%80%93-t-sql-new-line-char/</link>
		<comments>http://dev.digi-corp.com/2009/07/sql-server-%e2%80%93-difference-between-line-feed-n-and-carriage-return-r-%e2%80%93-t-sql-new-line-char/#comments</comments>
		<pubDate>Sun, 05 Jul 2009 16:42:42 +0000</pubDate>
		<dc:creator>pinaldave</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Carriage Return]]></category>
		<category><![CDATA[New Line Feed]]></category>
		<category><![CDATA[pinaldave]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://dev.digi-corp.com/?p=876</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">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 – <strong>What is difference between Line Feed (\n) and Carriage Return (\r)?</strong></p>
<p style="text-align: justify;">Prior to continuing with this article let us first look into few synonyms for LF and CR.</p>
<p style="text-align: justify;">Line Feed – LF – \n – 0×0a – 10 (decimal)</p>
<p style="text-align: justify;">Carriage Return – CR – \r – 0×0D – 13 (decimal)</p>
<p style="text-align: justify;">Now that we have understood that we have two different options to get new line, the question that arises is – why is it so?</p>
<p style="text-align: justify;">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.</p>
<p style="text-align: justify;">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.</p>
<p style="text-align: justify;"><strong>Example 1: No new line feed char</strong></p>
<p style="text-align: justify;"><code style="font-size: 12px;"><span style="color: blue;">DECLARE </span><span style="color: #434343;">@NewLineChar </span><span style="color: blue;">AS CHAR</span><span style="color: gray;">(</span><span style="color: black;">2</span><span style="color: gray;">) </span><span style="color: blue;">= CHAR</span><span style="color: gray;">(</span><span style="color: black;">13</span><span style="color: gray;">) + </span><span style="color: blue;">CHAR</span><span style="color: gray;">(</span><span style="color: black;">10</span><span style="color: gray;">)<br />
</span><span style="color: blue;">PRINT </span><span style="color: gray;">(</span><span style="color: red;">'SELECT FirstLine AS FL SELECT SecondLine AS SL' </span><span style="color: gray;">)<br />
</span><span style="color: black;">GO</span></code></p>
<p style="text-align: justify;"><span style="color: black;"><img src="http://www.pinaldave.com/bimg/lf1.png" alt="" width="494" height="144" /><br />
</span></p>
<p style="text-align: justify;"><strong>Example 2: With new line feed char</strong></p>
<p style="text-align: left;"><code style="font-size: 12px;"><span style="color: blue;">DECLARE </span><span style="color: #434343;">@NewLineChar </span><span style="color: blue;">AS CHAR</span><span style="color: gray;">(</span><span style="color: black;">2</span><span style="color: gray;">) </span><span style="color: blue;">= CHAR</span><span style="color: gray;">(</span><span style="color: black;">13</span><span style="color: gray;">) + </span><span style="color: blue;">CHAR</span><span style="color: gray;">(</span><span style="color: black;">10</span><span style="color: gray;">)<br />
</span><span style="color: blue;">PRINT </span><span style="color: gray;">(</span><span style="color: red;">'SELECT FirstLine AS FL ' </span><span style="color: gray;">+</span><span style="color: #434343;">@NewLineChar </span><span style="color: gray;">+ </span><span style="color: red;">'SELECT SecondLine AS SL' </span><span style="color: gray;">)<br />
</span><span style="color: black;">GO<br />
</span></code></p>
<p style="text-align: justify;"><img src="http://www.pinaldave.com/bimg/lf2.png" alt="" width="476" height="174" /></p>
<p style="text-align: justify;">I hope my examples make things more clear to you all. Let me have your feedback on this article.</p>
<p style="text-align: justify;">Reference : <strong>Pinal Dave (<a href="http://blog.sqlauthority.com/" target="_blank">http://blog.SQLAuthority.com</a>)</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://dev.digi-corp.com/2009/07/sql-server-%e2%80%93-difference-between-line-feed-n-and-carriage-return-r-%e2%80%93-t-sql-new-line-char/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Sql Server automatically adjusts nearest 3 milliseconds on Date Selection Criteria</title>
		<link>http://dev.digi-corp.com/2009/07/sql-server-automatically-adjusts-nearest-3-milliseconds-on-date-selection-criteria/</link>
		<comments>http://dev.digi-corp.com/2009/07/sql-server-automatically-adjusts-nearest-3-milliseconds-on-date-selection-criteria/#comments</comments>
		<pubDate>Sun, 05 Jul 2009 06:02:35 +0000</pubDate>
		<dc:creator>kalpesh.patel</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[3 Milliseconds]]></category>
		<category><![CDATA[Adjust Date]]></category>
		<category><![CDATA[Date]]></category>
		<category><![CDATA[filter]]></category>

		<guid isPermaLink="false">http://dev.digi-corp.com/?p=688</guid>
		<description><![CDATA[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. [...]]]></description>
			<content:encoded><![CDATA[<p>Most of the time we grab the date and time using sql server GetDate() Function.</p>
<p>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.</p>
<p>It will be more clear by following example.</p>
<p>Create Table datetesting<br />
(<br />
PK_id INT IDENTITY,<br />
Datefield DateTime<br />
)</p>
<p>Insert into datetesting(DateField)<br />
Values (&#8217;1/2/09 00:00&#8242;)<br />
Insert into datetesting(DateField)<br />
Values (&#8217;1/2/09 23:59&#8242;)</p>
<p>Insert into datetesting(DateField)<br />
Values (&#8217;1/2/09 11:59:59.995 pm&#8217;)</p>
<p>Insert into datetesting(DateField)<br />
Values (&#8217;1/3/09&#8242;)</p>
<p>Now Execute the following query</p>
<p>Select * from datetesting where Datefield Between &#8217;1/2/9&#8242; AND &#8217;1/2/9 11:59:59.998 PM&#8217;</p>
<p>Result of the above query</p>
<p>PK_id        DateField<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
1        2009-01-02 00:00:00.000<br />
2        2009-01-02 23:59:00.000<br />
3        2009-01-02 23:59:59.997</p>
<p>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.</p>
<p>Select * from datetesting where Datefield Between &#8217;1/2/9&#8242; AND &#8217;1/2/9 11:59:59.999 PM&#8217;</p>
<p>PK_id        DateField<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
1    2009-01-02 00:00:00.000<br />
2    2009-01-02 23:59:00.000<br />
3    2009-01-02 23:59:59.997<br />
4    2009-01-03 00:00:00.000</p>
<p>So next time when you face wrong data by filter, don&#8217;t get perplexed, This may be the reason!</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.digi-corp.com/2009/07/sql-server-automatically-adjusts-nearest-3-milliseconds-on-date-selection-criteria/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to Convert Cursor into While Loop In Sqlserver ?</title>
		<link>http://dev.digi-corp.com/2009/06/how-to-convert-cursor-into-while-loop-in-sqlserver/</link>
		<comments>http://dev.digi-corp.com/2009/06/how-to-convert-cursor-into-while-loop-in-sqlserver/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 06:45:38 +0000</pubDate>
		<dc:creator>kuldip.bhatt</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Avoid Curosr]]></category>
		<category><![CDATA[Convert Cursor]]></category>
		<category><![CDATA[Cursor]]></category>
		<category><![CDATA[Remove Cursor]]></category>
		<category><![CDATA[While Loop]]></category>

		<guid isPermaLink="false">http://dev.digi-corp.com/?p=692</guid>
		<description><![CDATA[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. &#8211; Original Cursor [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>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.</p>
<p><strong>&#8211; Original Cursor Code &#8212; </strong></p>
<p style="padding-left: 30px;">Declare @fk_MedicationOrderId as Bigint<br />
Declare @AdminTime as Bigint</p>
<p style="padding-left: 30px;">declare CUR_MEDICATIONORDERID cursor FOR<br />
select<br />
fk_MedicationOrderId<br />
from<br />
tbl_medicationorderDetail_trn<br />
where<br />
Actiondate &gt; Getdate()</p>
<p style="padding-left: 30px;">OPEN CUR_MEDICATIONORDERID</p>
<p style="padding-left: 30px;">FETCH NEXT FROM CUR_MEDICATIONORDERID<br />
INTO @fk_MedicationOrderId</p>
<p style="padding-left: 30px;">WHILE @@FETCH_STATUS =0<br />
BEGIN</p>
<p style="padding-left: 60px;">Select @AdminTime=AdminTime from tbl_medicationorderDetail_trn<br />
where fk_medicationorderid = @fk_MedicationOrderId</p>
<p style="padding-left: 60px;">Update tbl_TempMedicationOrderDetail_trn<br />
set ActionTime = @AdminTime<br />
set @AdminTime = &#8221;</p>
<p style="padding-left: 30px;">FETCH NEXT FROM CUR_MEDICATIONORDERID<br />
INTO @fk_MedicationOrderId</p>
<p style="padding-left: 30px;">END</p>
<p style="padding-left: 30px;">CLOSE CUR_MEDICATIONORDERID<br />
DEALLOCATE CUR_MEDICATIONORDERID</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p><strong>&#8211; Modified Cursor Code (faster) &#8211;</strong></p>
<p style="padding-left: 30px;">Declare @fk_MedicationOrderId as Bigint<br />
Declare @AdminTime as Bigint</p>
<p style="padding-left: 30px;">Declare Table for the fields you need in the cursor.</p>
<p style="padding-left: 30px;">declare @IDList table (ID Bigint)</p>
<p style="padding-left: 30px;">Insert into @IDList<br />
select<br />
fk_MedicationOrderId<br />
from<br />
tbl_medicationorderDetail_trn<br />
where<br />
Actiondate &gt; Getdate()</p>
<p style="padding-left: 30px;">while (select count(ID) from @IDList) &gt; 0<br />
begin<br />
select top 1 @fk_MedicationOrderId = ID from @IDList</p>
<p style="padding-left: 60px;">Select @AdminTime=AdminTime from tbl_medicationorderDetail_trn<br />
where fk_medicationorderid = @fk_MedicationOrderId</p>
<p style="padding-left: 60px;">Update tbl_TempMedicationOrderDetail_trn<br />
set ActionTime = @AdminTime<br />
set @AdminTime = &#8221;</p>
<p style="padding-left: 30px;">delete from @IDList where ID = @fk_MedicationOrderId</p>
<p style="padding-left: 30px;">end</p>
<p><strong>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</strong></p>
<p>What I have done here is to convert <strong>&#8220;cursor&#8221;</strong> into <strong>&#8220;while loop&#8221;</strong>.<strong> </strong>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.</p>
<p>It helps in improving performance, I have personally tried it in many stored procedures.</p>
<p>Let me know if you find any other useful way of improving performance.</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.digi-corp.com/2009/06/how-to-convert-cursor-into-while-loop-in-sqlserver/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>CLR Stored Procedures and creating it step by step</title>
		<link>http://dev.digi-corp.com/2009/06/clr-stored-procedures-and-creating-it-step-by-step/</link>
		<comments>http://dev.digi-corp.com/2009/06/clr-stored-procedures-and-creating-it-step-by-step/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 12:28:38 +0000</pubDate>
		<dc:creator>virat.kothari</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[clr]]></category>
		<category><![CDATA[clr stored procedure]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[stored procedure]]></category>
		<category><![CDATA[virat]]></category>
		<category><![CDATA[virat kothari]]></category>

		<guid isPermaLink="false">http://dev.digi-corp.com/?p=707</guid>
		<description><![CDATA[Download code &#38; SQL statements: 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 &#38; business rules in database objects. In many cases we found C# or VB classes more powerful [...]]]></description>
			<content:encoded><![CDATA[<h5><span style="color: #000000;">Download code &amp; SQL statements:</span> <a href="http://dev.digi-corp.com/wp-content/uploads/2009/06/CLRDemo.zip"><img class="alignnone size-full wp-image-737" src="http://dev.digi-corp.com/wp-content/uploads/2009/06/BlueDownArrow.jpeg" alt="BlueDownArrow" width="20" height="22" /></a></h5>
<h2>Introduction:</h2>
<p>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 &amp; 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”.</p>
<h2>What is CLR Stored Procedure?</h2>
<p>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 &amp; type safety etc. So now, CLR Stored Procedures are .Net objects which run in the memory of database.</p>
<p>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.</p>
<p><img class="alignnone size-full wp-image-723" src="http://dev.digi-corp.com/wp-content/uploads/2009/06/0.PNG" alt="0" width="625" height="311" /></p>
<h2>When should I use CLR Stored Procedure?</h2>
<p>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.</p>
<h2>Benefits of CLR Stored Procedures:</h2>
<ol>
<li>Gives better results while executing complex logic, intense string operation or string manipulations, cryptography, accessing system resources and file management etc.</li>
<li>CLR Stored Procedures are managed codes so ensures type safety, memory management etc.</li>
<li>Better code management and provides object oriented programming capability thus enables encapsulation, polymorphism &amp; inheritance.</li>
<li>Convenient for programmer as CLR Stored Procedures can be written in C#, VB or any other language that .Net Framework supports.</li>
<li>CLR Stored Procedures can also be used with Oracle 10g Release 2 or later versions.</li>
<li>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.</li>
<li>Deployment may be difficult in some scenarios.</li>
</ol>
<h2>Drawbacks of CLR Stored Procedures:</h2>
<ol>
<li>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.</li>
<li>Deployment may be difficult in some scenarios.</li>
</ol>
<h2>Standard Stored Procedures vs. CLR Stored Procedures:</h2>
<p>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.</p>
<ol>
<li>When the program requires complex logic or business rules.</li>
<li>When the flow is CPU intensive. CLR Stored Procedures gives better results as they are in complied form and managed one.</li>
<li>The tasks which are not possible in TSQL, accessing system resources, cryptography, accessing web services etc.</li>
<li>In option of Extended Stored Procedures. One should always consider CLR Stored Procedures before going for Extended Stored Procedures.</li>
<li>An operation requires higher data safety.</li>
</ol>
<h2>Creating CLR Stored Procedure step by step:</h2>
<p>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.</p>
<p><strong>Application development specification:</strong></p>
<ul>
<li>IDE: Visual Studio 2008</li>
<li>Framework: 3.5 with SP 1</li>
<li>Language: C# 3.0</li>
<li>Database MS SQL Server 2005 Express edition</li>
</ul>
<p><strong>Steps to create CLR Stored Procedure:</strong></p>
<p>1) Open Microsoft Visual Studio &gt;&gt; Click on New Project &gt;&gt; Select Database Projects &gt;&gt; SQL Server Project.</p>
<p><img class="alignnone size-full wp-image-714" src="http://dev.digi-corp.com/wp-content/uploads/2009/06/1.PNG" alt="1" width="628" height="457" /></p>
<p>2) You can choose reference of existing database connection or click on Add New Reference.</p>
<p><img class="alignnone size-full wp-image-715" src="http://dev.digi-corp.com/wp-content/uploads/2009/06/2.PNG" alt="2" width="358" height="402" /></p>
<p>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.</p>
<p><img class="alignnone size-full wp-image-716" src="http://dev.digi-corp.com/wp-content/uploads/2009/06/3.PNG" alt="3" width="511" height="752" /></p>
<p>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.</p>
<p><img class="alignnone size-full wp-image-717" src="http://dev.digi-corp.com/wp-content/uploads/2009/06/4.PNG" alt="4" width="582" height="191" /></p>
<p>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 &gt;&gt; Click on Add &gt;&gt; Stored Procedure.</p>
<p><img class="alignnone size-full wp-image-718" src="http://dev.digi-corp.com/wp-content/uploads/2009/06/5.PNG" alt="5" width="628" height="394" /></p>
<p>6) Add new procedure from the installed templates as shown in following screen. Give proper name to it.</p>
<p><img class="alignnone size-full wp-image-719" src="http://dev.digi-corp.com/wp-content/uploads/2009/06/6.PNG" alt="6" width="628" height="409" /></p>
<p>7) Once you select the template, it will create .cs file with the content shown in following image.</p>
<p><img class="alignnone size-full wp-image-720" src="http://dev.digi-corp.com/wp-content/uploads/2009/06/7.PNG" alt="7" width="628" height="394" /></p>
<p>8 ) Add following code in the method already created. Pass &#8220;context connection=true&#8221; 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 &gt;&gt; Click on Build Solution. Also click on Build menu &gt;&gt; Deploy solution. This will deploy the assembly to the database for which we have made connection initially.</p>
<p><img class="alignnone size-full wp-image-721" src="http://dev.digi-corp.com/wp-content/uploads/2009/06/8.PNG" alt="8" width="628" height="394" /></p>
<p>9) Now, select the database &gt;&gt; Programmability. Right click on Stored Procedures &gt;&gt; Click on Refresh. The list of Stored Procedures should show one newly added stored procedure. Also right click on Assemblies &gt;&gt; click on Refresh. This should show newly added Assembly. Also, enable CLR Stored Procedure by following query.</p>
<p>sp_configure &#8216;clr enabled&#8217;, 1</p>
<p>Run following query to take effect or above query.</p>
<p>RECONFIGURE</p>
<p>Now, execute the stored procedure. It should give similar results shown in following screen.</p>
<p><img class="alignnone size-full wp-image-722" src="http://dev.digi-corp.com/wp-content/uploads/2009/06/9.PNG" alt="9" width="628" height="394" /></p>
<h2>SQL statements used in the demo:</h2>
<p>Following is the queries to create database, create table, insert records in the table etc.</p>
<p>&#8211;Create a new databse for demo</p>
<p>CREATE DATABASE DbForClrDemo</p>
<p>&#8211;Use database</p>
<p>USE DbForClrDemo</p>
<p>&#8211;Create table for CustomerSalesInformation</p>
<p>CREATE TABLE [dbo].[CustomerSalesInformation](</p>
<p>[Id] [int] IDENTITY(1,1) NOT NULL,</p>
<p>[Name] [varchar](50) NOT NULL,</p>
<p>[Sales] [decimal](18, 2) NOT NULL DEFAULT ((0)),</p>
<p>CONSTRAINT [PK_CustomerSalesInformation] PRIMARY KEY CLUSTERED</p>
<p>(</p>
<p>[Id] ASC</p>
<p>)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]</p>
<p>) ON [PRIMARY]</p>
<p>&#8211;Insert dummy data to CustomerSalesInformation table</p>
<p>INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (&#8216;Virat Kothari&#8217;, 50000)</p>
<p>INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (&#8216;Dhruval Shah&#8217;, 5000)</p>
<p>INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (&#8216;Urvish Sheth&#8217;, 15000)</p>
<p>INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (&#8216;Rakesh Bajania&#8217;, 25000)</p>
<p>INSERT INTO [dbo].[CustomerSalesInformation]([Name], [Sales]) VALUES (&#8216;Dhaval Shah&#8217;, 150000)</p>
<p>&#8211;Enable CLR Stored Procedure in database</p>
<p>sp_configure &#8216;clr enabled&#8217;, 1</p>
<p>&#8211;Run following statuement to take effect of above statement</p>
<p>RECONFIGURE</p>
<p>&#8211;Now execute our CLR Stored Procedure. Remember &#8220;ClrDemo&#8221; is name of our Stored Procedure</p>
<p>EXEC [dbo].ClrDemo</p>
<h2>Conclusion:</h2>
<p>CLR Stored procedures are very simple and can be used in most complex scenarios.</p>
<h2>Bibliography:</h2>
<ol>
<li>MSDN (http://msdn.microsoft.com/en-us/library/ms131094.aspx)</li>
<li>Code project</li>
<li>http://searchsqlserver.techtarget.com/generic/0,295582,sid87_gci1251402,00.html</li>
</ol>
<h3><span style="color: #000000;">Reference : <strong>Virat Kothari (</strong><a title="Virat Kothari" href="http://viratkothari.wordpress.com/" target="_blank">www.viratkothari.wordpress.com</a><strong>)</strong></span></h3>
]]></content:encoded>
			<wfw:commentRss>http://dev.digi-corp.com/2009/06/clr-stored-procedures-and-creating-it-step-by-step/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>SQL SERVER – sqlcmd – Using a Dedicated Administrator Connection to Kill Currently Running Query</title>
		<link>http://dev.digi-corp.com/2009/06/sql-server-%e2%80%93-sqlcmd-%e2%80%93-using-a-dedicated-administrator-connection-to-kill-currently-running-query/</link>
		<comments>http://dev.digi-corp.com/2009/06/sql-server-%e2%80%93-sqlcmd-%e2%80%93-using-a-dedicated-administrator-connection-to-kill-currently-running-query/#comments</comments>
		<pubDate>Sat, 13 Jun 2009 07:26:53 +0000</pubDate>
		<dc:creator>pinaldave</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[pinaldave]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[sqlcmd]]></category>
		<category><![CDATA[Sqlserver]]></category>

		<guid isPermaLink="false">http://dev.digi-corp.com/?p=681</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">People are judged from their questions and not their answers. I received wonderful question the other day.</p>
<p style="text-align: justify;"><em><strong>How sqlcmd can be used along with currently running query script posted on your blog?</strong></em></p>
<p style="text-align: justify;">Please read following two posts before continuing this article as they cover background of this article.</p>
<p style="text-align: justify;"><strong><a href="http://blog.sqlauthority.com/2009/01/06/sql-server-interesting-observation-using-sqlcmd-from-ssms-query-editor/" target="_blank">SQL SERVER – Interesting Observation – Using sqlcmd From SSMS Query Editor</a></strong></p>
<p style="text-align: justify;"><strong><a href="http://blog.sqlauthority.com/2009/01/07/sql-server-find-currently-running-query-t-sql/" target="_blank">SQL SERVER – Find Currently Running Query – T-SQL</a></strong></p>
<p style="text-align: justify;">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.</p>
<p style="text-align: justify;">Let us see how we can use DAC using sqlcmd.</p>
<p style="text-align: justify;">Connect SQL Server using sqlcmd and -A option which will establish DAC.</p>
<p style="text-align: justify;"><em><strong>C:\&gt;sqlcmd -S localhost -U sa -P dev -d master -A</strong></em></p>
<p style="text-align: justify;"><img class="alignnone" src="http://www.pinaldave.com/bimg/sqlcmd_1.jpg" alt="" width="500" height="308" /></p>
<p style="text-align: justify;">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.</p>
<p style="text-align: justify;"><em><strong>Following query is just for test purpose and not part of solution.</strong></em></p>
<p style="text-align: justify;"><code style="font-size: 12px;"><span style="color: blue;">USE </span><span style="color: black;">AdventureWorks<br />
GO<br />
</span><span style="color: blue;">SELECT </span><span style="color: gray;">*<br />
</span><span style="color: blue;">FROM </span><span style="color: black;">Person.Address<br />
</span><span style="color: gray;">CROSS </span><span style="color: blue;">JOIN </span><span style="color: black;">Person.Address a1<br />
</span><span style="color: gray;">CROSS </span><span style="color: blue;">JOIN </span><span style="color: black;">Person.Address a2<br />
</span><span style="color: gray;">CROSS </span><span style="color: blue;">JOIN </span><span style="color: black;">Person.Address a3<br />
</span><span style="color: gray;">CROSS </span><span style="color: blue;">JOIN </span><span style="color: black;">Person.Address a4<br />
</span><span style="color: gray;">CROSS </span><span style="color: blue;">JOIN </span><span style="color: black;">Person.Address a5<br />
</span><span style="color: gray;">CROSS </span><span style="color: blue;">JOIN </span><span style="color: black;">Person.Address a6<br />
</span><span style="color: gray;">CROSS </span><span style="color: blue;">JOIN </span><span style="color: black;">Person.Address a7<br />
</span><span style="color: gray;">CROSS </span><span style="color: blue;">JOIN </span><span style="color: black;">Person.Address a8<br />
</span><span style="color: gray;">CROSS </span><span style="color: blue;">JOIN </span><span style="color: black;">Person.Address a9<br />
GO </span></code></p>
<p style="text-align: justify;"><img class="alignnone" src="http://www.pinaldave.com/bimg/sqlcmd_3.jpg" alt="" width="499" height="614" /></p>
<p style="text-align: justify;">Once successfully connected it will provide prompt 1&gt; enter following T-SQL query which will give SessionID of currently running query along with its elapsed time.</p>
<p style="text-align: justify;"><code style="font-size: 12px;"><span style="color: blue;">SELECT<br />
</span><span style="color: black;">req.session_id</span><span style="color: gray;">,<br />
</span><span style="color: black;">req.status</span><span style="color: gray;">,<br />
</span><span style="color: black;">req.total_elapsed_time<br />
</span><span style="color: blue;">FROM </span><span style="color: black;">sys.dm_exec_requests req<br />
</span><span style="color: blue;">WHERE </span><span style="color: black;">status </span><span style="color: blue;">= </span><span style="color: red;">'running'<br />
</span><span style="color: gray;">AND </span><span style="color: black;">req.total_elapsed_time </span><span style="color: gray;">&gt; </span><span style="color: black;">1</span></code></p>
<p style="text-align: justify;"><img class="alignnone" src="http://www.pinaldave.com/bimg/sqlcmd_2.jpg" alt="" width="500" height="317" /></p>
<p style="text-align: justify;">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.</p>
<p style="text-align: justify;"><code style="font-size: 12px;"><span style="color: blue;">KILL </span><span style="color: black;">52</span></code></p>
<p style="text-align: justify;"><img class="alignnone" src="http://www.pinaldave.com/bimg/sqlcmd_4.jpg" alt="" width="500" height="317" /></p>
<p style="text-align: justify;">Once above query has run it will kill our example long running query and give following error.</p>
<p style="text-align: justify;"><span style="color: #ff0000;"><em>Msg 233, Level 20, State 0, Line 0</em></span></p>
<p><em>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.)</em></p>
<p style="text-align: justify;"><img class="alignnone" src="http://www.pinaldave.com/bimg/sqlcmd_5.jpg" alt="" width="500" height="616" /></p>
<p style="text-align: justify;">sqlcmd is really useful utility of SQL Server and it comes in handy when server is not responsive. I strongly suggest to <strong>bookmark </strong>this article as it can come to rescue when nothing works and SQL Server is unresponsive.</p>
<p style="text-align: justify;">Reference : <strong>Pinal Dave (<a href="http://blog.sqlauthority.com/" target="_blank">http://blog.SQLAuthority.com</a>)</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://dev.digi-corp.com/2009/06/sql-server-%e2%80%93-sqlcmd-%e2%80%93-using-a-dedicated-administrator-connection-to-kill-currently-running-query/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to Find and Replace in Update Query?</title>
		<link>http://dev.digi-corp.com/2009/06/how-to-find-and-replace-in-update-query/</link>
		<comments>http://dev.digi-corp.com/2009/06/how-to-find-and-replace-in-update-query/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 12:07:01 +0000</pubDate>
		<dc:creator>kuldip.bhatt</dc:creator>
				<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Find and Replace]]></category>
		<category><![CDATA[Patindex]]></category>
		<category><![CDATA[Replace]]></category>
		<category><![CDATA[Replace in Sql]]></category>
		<category><![CDATA[Sqlserver]]></category>
		<category><![CDATA[Stuff]]></category>

		<guid isPermaLink="false">http://dev.digi-corp.com/?p=580</guid>
		<description><![CDATA[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 &#8217;04:30,05:00,05:30,06:00&#8242; i.e coma separated values in one field of a table. Now, how do I replace &#8217;06:00&#8242; with &#8217;06:30&#8242; in a query ? Let do it here. Declare the Variables. DECLARE  @find      varchar(255), @replace   [...]]]></description>
			<content:encoded><![CDATA[<p>How to Find and Replace in Update Query ?</p>
<p>For e.g. I have field name orderFreQuencyvalues in tbl_OrderFrequency_mst</p>
<p>This Field contains values like &#8217;04:30,05:00,05:30,06:00&#8242; i.e coma separated values in one field of a table.</p>
<p>Now, how do I replace &#8217;06:00&#8242; with &#8217;06:30&#8242; in a query ? Let do it here.</p>
<p>Declare the Variables.</p>
<p>DECLARE  @find      varchar(255),<br />
@replace   varchar(255),<br />
@patfind   varchar(255)</p>
<p>Initialize the values for the variables.</p>
<p>SELECT   @find    = &#8217;06:00&#8242;,<br />
@replace = &#8217;06:30&#8242;</p>
<p>SELECT   @patfind = &#8216;%&#8217; + @find + &#8216;%&#8217;</p>
<p>Run the below query.</p>
<p>UPDATE   tbl_OrderFrequency_mst<br />
SET      orderFreQuencyvalues = STUFF( orderFreQuencyvalues,<br />
PATINDEX( @patfind, orderFreQuencyvalues ),<br />
DATALENGTH( @find ),<br />
@replace )</p>
<p>WHERE    orderFreQuencyvalues LIKE @patfind</p>
<p>STUFF( text or Field Name , start , length , Replace value)</p>
<p>Purpose of STUFF:<br />
Deletes a specified length of characters and inserts another set of characters at a specified starting point</p>
<p>Patindex( FindValue , text or Field Name)<br />
Find the Index where Findvalue Start</p>
<p>Datalength( TextData )<br />
Return the lenght of the text</p>
<p>I hope you find this useful somewhere.</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.digi-corp.com/2009/06/how-to-find-and-replace-in-update-query/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

