<?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>Sqlserver007 &#187; TSQL Development</title>
	<atom:link href="http://www.sqlserver007.com/category/tsql-general/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sqlserver007.com</link>
	<description>Blog on SQL SERVER and Business Intelligence  by Vivekanand Serou</description>
	<lastBuildDate>Fri, 21 May 2010 11:37:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>SQL SERVER :Date and Time Dimensions in T-SQL using CTE</title>
		<link>http://www.sqlserver007.com/2010/01/20/sql-server-date-and-time-dimensions-in-t-sql-using-cte/</link>
		<comments>http://www.sqlserver007.com/2010/01/20/sql-server-date-and-time-dimensions-in-t-sql-using-cte/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 13:27:20 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[Business Intelligence]]></category>
		<category><![CDATA[SSAS]]></category>
		<category><![CDATA[TSQL Development]]></category>
		<category><![CDATA[cte]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.sqlserver007.com/?p=506</guid>
		<description><![CDATA[Everytime we create a cube for analysis services Date and Time Dimensions are needed to slice and dice the historical Data. Sql Server Analysis Services uses the Time Intelligence Features to populate the date and time. Its posted in detail in this blog. However we need to use them in our relational Databases to do [...]]]></description>
			<content:encoded><![CDATA[<p>Everytime we create a cube for analysis services Date and Time Dimensions are needed to slice and dice the historical Data. Sql Server Analysis Services uses the Time Intelligence Features to populate the date and time. Its posted in detail in this <a href="http://www.mssqltips.com/tip.asp?tip=1454">blog</a>.</p>
<p>However we need to use them in our relational Databases to do some adhoc reporting. I always use the following CTE&#8217;s to create Date and Time Dimensions. The good thing about CTE is you can recursively loop through the data till you get the desired result. </p>
<p><strong>DATE DIMENSION :</strong></p>
<p>I got the Date Dimension idea originally from <a href="http://consultingblogs.emc.com/jamiethomson/archive/2007/01/11/T_2D00_SQL_3A00_-Generate-a-list-of-dates.aspx">JamieT (Jamie Thomson,MVP SQL Server) &#8216;s blog.</a></p>
<pre>
with DateCTE  as
(
	select cast ('01-Jan-2009' as datetime)   Datevalue
	union all
	select datevalue + 1
	from DateCTE where datevalue + 1 < = '31-Dec-2020'
)
select cast(datevalue as int ) as DateID
,datename(year,DateValue) as [Year]
,dateName(Month,DateValue) as [Month]
,datename(d,datevalue) as [datenumber]
,datename(Week,Datevalue) as [Week]
,datename(DW,Datevalue) as [Day]
,Datevalue  as [Date]
from DateCTE
order by Datevalue
option (maxrecursion 0)
</pre>
<p><strong>TIME DIMENSION :</strong></p>
</pre>
<pre>  with HourCTE(Hour,Minute) as
  (
  select 0 as Hour , 0 as Minute
  union all
  select Hour , Minute + 1
  from HourCTE
  where Minute + 1 < 60
  ),
   MinuteCTE(Hour,minute) as
  (
    select Hour, Minute from HourCTE
	union all
	select Hour + 1 ,Minute from MinuteCTE
	where Hour + 1 < 24
)
select * from minuteCTE
order by Hour ,Minute </pre>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sqlserver007.com/2010/01/20/sql-server-date-and-time-dimensions-in-t-sql-using-cte/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Happy New Year in TSQL</title>
		<link>http://www.sqlserver007.com/2009/12/31/happy-new-year-in-tsql/</link>
		<comments>http://www.sqlserver007.com/2009/12/31/happy-new-year-in-tsql/#comments</comments>
		<pubDate>Thu, 31 Dec 2009 10:00:55 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[TSQL Development]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.sqlserver007.com/?p=390</guid>
		<description><![CDATA[I did use SQL String manipulations a lot this year. I want to show an example of how to use CHAR. Open your Management Studio &#8211; and paste the following in your Query Window SELECT CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15) + CHAR(15) + CHAR(15) + CHAR(15) + CHAR(13) + CHAR(72) + CHAR(65) + CHAR(80) + CHAR(80)+ CHAR(89) + ' [...]]]></description>
			<content:encoded><![CDATA[<p>I did use SQL String manipulations a lot this year.  I want to show an example of how to use CHAR.</p>
<p>Open your Management Studio &#8211; and paste the following in your Query Window</p>
<pre>
SELECT CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15) + CHAR(15) + CHAR(15) + CHAR(15) + CHAR(13)
+ CHAR(72) + CHAR(65) + CHAR(80) + CHAR(80)+ CHAR(89) + ' ' + CHAR(78) + CHAR(69)+CHAR(87)+ ' ' + CHAR(89)+ CHAR(69)+ CHAR(65) + CHAR(82)
+CHAR(13)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15)+CHAR(15) + CHAR(15) + CHAR(15) + CHAR(15)
</pre>
<p>Run the Query(Try Pressing Ctrl-T and run the Query again).</p>
<p>Want to know what each <strong>CHAR</strong> value represent ?<br />
Run the following:<br />
 
<pre>
DECLARE @i int
SET @i = 1
WHILE @i &lt; = 256 Begin PRINT CHAR(@i) + ' --&gt; ' + CONVERT(VARCHAR,@i)
SET @i = @i + 1
END
</pre>
<p>Enjoy!!!</p>
<p>Wish you all a Happy New Year.</p>
<p><a href="http://twitter.com/vivekserou">@VivekSerou</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sqlserver007.com/2009/12/31/happy-new-year-in-tsql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a simple FrontEnd using Reporting Services and Merge</title>
		<link>http://www.sqlserver007.com/2009/12/07/creating-reporting-services-as-frontend-using-merge/</link>
		<comments>http://www.sqlserver007.com/2009/12/07/creating-reporting-services-as-frontend-using-merge/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 23:03:53 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[Business Intelligence]]></category>
		<category><![CDATA[SSRS]]></category>
		<category><![CDATA[TSQL Development]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.sqlserver007.com/?p=321</guid>
		<description><![CDATA[Problem: A Business User wants to update/insert/delete the values in a table that sits in the metadata of the Datawarehouse on a regular basis. Based on these values numerous calculations will be done in the warehouse which generates a data driven Report on a weekly basis. Initially I got the following Solutions 1. Create a [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Problem: </strong><br />
A Business User wants to update/insert/delete the values in a table that sits in the metadata of the Datawarehouse on a regular basis. Based on these values numerous calculations will be done in the warehouse which generates a data driven Report on a weekly basis.</p>
<p><strong>Initially I got the following Solutions</strong><br />
1. Create a frontend app for the user to populate the values (the most common Global solution)<br />
2. Ask the user to populate the values in an excel file with the columns in specific format so that I can use my SSIS to do the lookup with the original table and update/delete/insert based on the values.( But there are lot of things to consider when using excel like  Problems with incorrect format of excel files and maintaining them.)</p>
<p>So when I was reviewing the <a href="http://technet.microsoft.com/en-us/library/bb510625.aspx">Merge</a> feature in TSQL 2008, an idea stuck in mind</p>
<p>The solution I ended up doing was</p>
<p><strong>Creating a Reporting services Report that takes the values as parameter and use the MERGE statement to insert/update/delete the values in the backend table</strong></p>
<p><strong>Here is the Example of what I mean:</strong></p>
<pre>
create table CricketRuns
(
PlayerID int identity(1,1),
PlayerName nvarchar(max),
Runs int,
Average float
)
go

insert into CricketRuns
select 'Sachin Tendulkar',17000,45.23
union
select 'Ricky Ponting',12000,41.08
union
select 'Kevin Peiterson',4000,46.00
union
select 'Chris Gayle',7000,34.87
union
select 'Jacques Kallis',11000,42.09
union
select 'Ross Taylor',2500,41.00
go
 </pre>
<p>So the table looks like</p>
<p><img src="http://www.sqlserver007.com/wp-content/uploads/2009/12/InitialResults1.jpg" alt="InitialResults" title="InitialResults" width="267" height="143" class="aligncenter size-full wp-image-325" /></p>
<p>I created this procedure using the Merge Statement that will insert / delete / update based on the players name</p>
<pre>
create procedure uspInsertRuns
	(
		@PlayerName nvarchar(max)
		,@Runs int
		,@Average float
		,@status nvarchar(100)
	)
		as
	Merge into CricketRuns as Target
	using
		(select @PlayerName,@Runs,@Average,@status) as source(Playername,runs,Average,Status)
	on
		(Target.Playername = source.PlayerName)
		when matched and Source.Status = 'D' then
		Delete
		when matched then
		update set runs = source.runs , Average = source.Average
		when not matched then
		insert (PlayerName,runs,Average)  values (source.PlayerName,source.runs,source.Average);

		select PlayerName,Runs,Average from CricketRuns order by PlayerID
 </pre>
<p>So you can insert,delete or update as below</p>
<p><strong>exec uspInsertRuns &#8216;Andrew Strauss&#8217;,2000,35,&#8221;  &#8211;> Insert<br />
exec uspInsertRuns &#8216;Virendar Shewag&#8217;,5000,37,&#8221; &#8211;> Insert<br />
exec uspInsertRuns &#8216;Ross Taylor&#8217;,0,0,&#8217;D&#8217; &#8211;> Delete<br />
exec uspInsertRuns &#8216;Sachin Tendulkar&#8217;,20000,45,&#8221; &#8211;> Update</strong></p>
<p>Just add the proc in a reporting services and expose it to the business user and thats it..A frontend using Reporting Services<br />
<img src="http://www.sqlserver007.com/wp-content/uploads/2009/12/ReportingServices.jpg" alt="ReportingServices" title="ReportingServices" width="643" height="456" class="aligncenter size-full wp-image-335" /></p>
<p>So without any excel management or creating a .net frontend  reporting services has done the job.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sqlserver007.com/2009/12/07/creating-reporting-services-as-frontend-using-merge/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>List of Temp Tables in your SQL server</title>
		<link>http://www.sqlserver007.com/2009/11/15/list-of-temp-tables-in-your-sql-server/</link>
		<comments>http://www.sqlserver007.com/2009/11/15/list-of-temp-tables-in-your-sql-server/#comments</comments>
		<pubDate>Sun, 15 Nov 2009 14:23:18 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[TSQL Development]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.sqlserver007.com/?p=318</guid>
		<description><![CDATA[select create_date,modify_date,OBJECT_NAME(object_id) as TableName from tempdb.sys.objects where name like &#8216;%#%&#8217;]]></description>
			<content:encoded><![CDATA[<p>select create_date,modify_date,OBJECT_NAME(object_id)  as TableName<br />
 from tempdb.sys.objects<br />
where name like &#8216;%#%&#8217;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sqlserver007.com/2009/11/15/list-of-temp-tables-in-your-sql-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Encryption in SQL SERVER using SSIS</title>
		<link>http://www.sqlserver007.com/2009/11/07/encryption-in-sql-server-using-ssis/</link>
		<comments>http://www.sqlserver007.com/2009/11/07/encryption-in-sql-server-using-ssis/#comments</comments>
		<pubDate>Sat, 07 Nov 2009 15:37:36 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[SSIS]]></category>
		<category><![CDATA[TSQL Development]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.sqlserver007.com/?p=288</guid>
		<description><![CDATA[I have been recently working on an Sql Server Encryption Project. It includes getting the data from a source and importing them into the Datawarehouse via the ETL(SSIS in this case) and then Encrypting it. I decided to blog on Encryption to share my experience. a. When you Encrypt the Data in SSIS make sure [...]]]></description>
			<content:encoded><![CDATA[<p>I have been recently working on an Sql Server Encryption Project. It includes getting the data from a source and importing them into the Datawarehouse via the ETL(SSIS in this case) and then Encrypting it. I decided to blog on Encryption to share my experience.</p>
<p>a. When you Encrypt the Data in SSIS make sure you Encrypt in Batches(i.e dont encrypt the same data again).<br />
b. The datatypes should be valid for the Encrypted Content and should have enough space to store it(I used nvarchar(max))</p>
<p>Below is a small Example of the Encryption Process:</p>
<p><strong>Encrypting the Database</strong></p>
<pre>
use EncryptionTest

--Create a Master Key by Encryption
create master key Encryption by password = 'Sql5erver'

--Create the Certificate
create certificate testcert with Subject = 'Testing the Symmetric Encryption'

--Create the Symmetric Key with Algorithm and Encrypt it with the certificate
create Symmetric Key testkey with algorithm =  AES_256 encryption by certificate testcert;
</pre>
<p><strong>Sample Tables and Data</strong></p>
<pre>
create Database Encryptiontest
go

create table Source
(
	UserID int
	,[Name] varchar(100)
	,Password varchar(max)
)
go

insert into Source
select 1,'Vivek','Sqlserver007'
union
select 2,'Jermey','MungingData'
union
select 3,'Marcus','SirMarcus'
union
select 4,'Cesare','Berlusconi'
go

create table EncryptedData
(
	userID int
	,[Name] varchar(100)
	,EncryptedPassword nvarchar(max)
	,Logid int
)

go
</pre>
<p><strong><u>Procedure for Encryption</u></strong></p>
<p>The Detailed Syntax for <strong>EncryptbyKey </strong>is given in this <a href="http://technet.microsoft.com/en-us/library/ms174361.aspx">MSDN </a>article</p>
<pre>
create procedure EncryptData
(
	@Logid int
)

as

Open Symmetric Key Testkey Decryption by Certificate TestCert

update EncryptedData
set EncryptedPassword = ENCRYPTBYKEY(Key_guid('testkey'),EncryptedPassword) where Logid = @Logid
</pre>
<p>Now Coming to the SSIS Task. I have used the Logid as the variable which controls the records to be encrypted in every flow(i.e the Log id changes for every iteration of the dataflow task). Once the records are transferred to the Destination table EncryptedData the procedure Encryptdata @Logid is executed.<br />
<br />
<img src="http://www.sqlserver007.com/wp-content/uploads/2009/11/SSISTask.jpg" alt="SSISTask" title="SSISTask" width="355" height="290" class="aligncenter size-full wp-image-295" /></p>
<p><strong>Variables and the DataSourcetask</strong></p>
<p>
<img src="http://www.sqlserver007.com/wp-content/uploads/2009/11/Encryption_DataFlow.jpg" alt="Encryption_DataFlow" title="Encryption_DataFlow" width="833" height="464" class="aligncenter size-full wp-image-296" /></p>
<p><strong>DataFlow task and Derived Column</strong><br />
<br />
<img src="http://www.sqlserver007.com/wp-content/uploads/2009/11/DataFlow_DerivedColumn.jpg" alt="DataFlow_DerivedColumn" title="DataFlow_DerivedColumn" width="623" height="705" class="aligncenter size-full wp-image-298" /></p>
<p><strong><u>How to Decrypt the Data?</u></strong></p>
<p>Once the Data is encrypted the table is displayed as follows</p>
<p><img src="http://www.sqlserver007.com/wp-content/uploads/2009/11/EncryptedData.jpg" alt="EncryptedData" title="EncryptedData" width="272" height="179" class="aligncenter size-full wp-image-304" /></p>
<p>For Decryption the End user should have the following permissions<br />
<a href="http://msdn.microsoft.com/en-us/library/ms186278.aspx">Grant Control on Certificate</a><br />
<a href="http://msdn.microsoft.com/en-us/library/ms179887.aspx">Grant View Definition on Symmetric Key</a></p>
<p>Following is the way to Decrypt. You need to open the Symmetric key to Decrypt it.</p>
<pre>
Open Symmetric Key TestKey Decryption by Certificate TestCert

select UserID,[name],CAST(DecryptByKey(EncryptedPassword) as nvarchar) as Password from
EncryptedData
 </pre>
<p>The following are the DMV&#8217;s(Dynamic Management Views) that can be used for Encryption</p>
<pre>
--Checking the Symmetric keys
select * From sys.symmetric_keys

--Checking the certificates
select  * from sys.certificates

--Checking for any openkeys
select * From sys.openkeys
</pre>
<p>There are some good articles on Encryption that may be useful to you in future.</p>
<p><a href="http://technet.microsoft.com/en-us/library/ms189586.aspx">Encryption HierArchy</a><br />
<a href="http://blogs.technet.com/keithcombs/archive/2005/11/24/sql-server-2005-data-encryption.aspx">http://blogs.technet.com/keithcombs/archive/2005/11/24/sql-server-2005-data-encryption.aspx</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sqlserver007.com/2009/11/07/encryption-in-sql-server-using-ssis/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Checking TSQL in SQL Server Reporting Services Datasets</title>
		<link>http://www.sqlserver007.com/2009/10/13/checking-tsql-in-sql-server-reporting-services-datasets/</link>
		<comments>http://www.sqlserver007.com/2009/10/13/checking-tsql-in-sql-server-reporting-services-datasets/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 12:31:27 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[SSRS]]></category>
		<category><![CDATA[TSQL Development]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.sqlserver007.com/?p=278</guid>
		<description><![CDATA[Recently I have been checking all the Dependencies on the Reports in SSRS(Sql server Reporting Services) because of a Major deployment on the ETL. The ETL change was to accomodate the transfer of a few columns from old Table TableA to the new table TableB. Some of the Datasets in the Reports are Stored Procedures [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I have been checking all the Dependencies on the Reports in SSRS(Sql server Reporting Services) because of a Major deployment on the ETL. The ETL change was to accomodate the transfer of a few columns from old Table TableA to the new table TableB. Some of the Datasets in the Reports are Stored Procedures and so I used <a href="http://www.sqlserver007.com/2009/04/06/sql-server-views-dependencies/">sp_depends </a> procedure to get the list of dependencies for TableA.</p>
<p>I also used the following TSQL to get list of objects in any database where the command text includes TableA. </p>
<p><strong><br />
DECLARE @tablename VARCHAR(100)<br />
SET @tablename = &#8216;%tableA%&#8217;</p>
<p>SELECT OBJECT_NAME(id) AS OBJECT ,TEXT,*   FROM syscomments WHERE TEXT LIKE @Tablename<br />
</strong></p>
<p>So far its good. But I found there are some TSQL written directly in the Reports Datasets(which I think is bad SSRS Development) and I cannot search them using the above two procedures.<br />
Upon researching in the ReportServer database the TSQL that is stored in the datasets are embedded in the <strong>CommandText </strong>tag of <strong>content</strong>column in the <strong>Catalog </strong>table.</p>
<p>The following is the script that illustrates it.<br />
<strong>DECLARE @tablename VARCHAR(100)</p>
<p>SET @tablename = &#8216;%TableA%&#8217;</p>
<p>   SELECT  PATH<br />
           , NAME<br />
           , CAST(CAST(content AS VARBINARY(MAX)) AS XML) AS ReportXML<br />
   FROM ReportServer.dbo.Catalog<br />
   WHERE CAST(content AS VARBINARY(MAX))   LIKE @tablename<br />
</strong><br />
You can even update the reports using the ReportXML column which I will discuss about it the future blogs.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sqlserver007.com/2009/10/13/checking-tsql-in-sql-server-reporting-services-datasets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DMV Report for Index Fragmentation and Statistics Update</title>
		<link>http://www.sqlserver007.com/2009/10/06/dmv-report-for-index-fragmentation-and-statistics-update/</link>
		<comments>http://www.sqlserver007.com/2009/10/06/dmv-report-for-index-fragmentation-and-statistics-update/#comments</comments>
		<pubDate>Tue, 06 Oct 2009 17:28:06 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[SQL Administration]]></category>
		<category><![CDATA[TSQL Development]]></category>
		<category><![CDATA[Admin]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://www.sqlserver007.com/?p=268</guid>
		<description><![CDATA[Recently the ETL load times of my Datawarehouse are increasing and so I decided to check the Indexes status on the tables . I found some fragmentation on the indexes and also some Statistics that are not being updated regularly . I searched online and found this blog by Ben Nevarez(SQL Blog). I decided to [...]]]></description>
			<content:encoded><![CDATA[<p>Recently the ETL load times of my Datawarehouse are increasing and so I decided to check the Indexes status on the tables . I found some fragmentation on the indexes and also some Statistics that are not being updated regularly . I searched online and found this blog by <a href="http://sqlblog.com/blogs/ben_nevarez/archive/2009/10/06/rebuilding-indexes-vs-updating-statistics.aspx">Ben Nevarez(SQL Blog)</a>.<br />
I decided to check the fragmentation levels of the Index after the ETL load is done daily on a regular basis. So I digged deep into the DMV&#8217;s and got this script below</p>
<pre>
select
OBJECT_NAME(ps.object_id) as TableName
,si.Name
,ps.Avg_Fragmentation_in_percent
,STATS_DATE(ss.object_id,ss.stats_id) as LastUpdatedStatistics
from
sys.dm_db_index_physical_stats(DB_ID(DB_NAME()),null,null,null,null) ps
join
sysindexes si
on
ps.object_id = si.id
and
ps.index_id = si.indid
left outer join
sys.stats ss
on
ss.object_id = ps.object_id
and
ss.name = si.name
where
ps.avg_fragmentation_in_percent > 10
order by
ps.avg_fragmentation_in_percent desc
</pre>
<p>I published the above query in my Reporting services suite of Operational Reports and check it daily morning. The report shows all the Indexes with more than 10% percent fragmentation along with Last updated Statistics time . If you want to go further.You may want to rebuild all the indexes that are above 20% fragmented in TSQL. If there is a better way of doing it please comment.</p>
<p><a href="http://www.twitter.com/vivekserou">@Vivekserou</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sqlserver007.com/2009/10/06/dmv-report-for-index-fragmentation-and-statistics-update/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Procedure to export text files</title>
		<link>http://www.sqlserver007.com/2009/09/23/procedure-to-export-text-files/</link>
		<comments>http://www.sqlserver007.com/2009/09/23/procedure-to-export-text-files/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 11:32:46 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[TSQL Development]]></category>
		<category><![CDATA[BCP]]></category>
		<category><![CDATA[Export]]></category>

		<guid isPermaLink="false">http://www.sqlserver007.com/?p=250</guid>
		<description><![CDATA[Recently I have read a lot of Blog posts on how to export files in different formats. But I use a custom procedure which exports text files in Pipe Delimited format using BCP.This procedure can be used in other processes for Output and Error Handling. Here is the Script for the procedure.You can modify the [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I have read a lot of Blog posts on how to export files in different formats. But I use a custom procedure which exports text files in Pipe Delimited format using BCP.This procedure can be used in other processes for Output and Error Handling.</p>
<p>Here is the Script for the procedure.You can modify the below procedure using any of the delimiters.</p>
<pre>
alter procedure Export_To_TextFile
(
	@OutputQuery varchar(5000)
	,@FileLocation varchar(400)
	,@FileName varchar(1000)
	,@ServerName varchar(100)
)

as

Declare @bcpcommand varchar(8000)

set @bcpcommand = 'bcp "' + @OutputQuery + '" queryout ' + @FileLocation + @FileName + ' ' + CHAR(13)
+ '-c -t" | " -T -S ' + @ServerName

Exec master..xp_cmdshell @bcpcommand 
</pre>
<p>Here is how I call the procedure </p>
<p><img src="http://www.sqlserver007.com/wp-content/uploads/2009/09/ExportToTextFile_Results1.png" alt="ExportToTextFile_Results" title="ExportToTextFile_Results" width="408" height="105" class="aligncenter size-full wp-image-257" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sqlserver007.com/2009/09/23/procedure-to-export-text-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Problem with SQL Server numeric data : Error converting data type varchar to numeric.</title>
		<link>http://www.sqlserver007.com/2009/09/08/error-converting-data-type-varchar-to-numeric/</link>
		<comments>http://www.sqlserver007.com/2009/09/08/error-converting-data-type-varchar-to-numeric/#comments</comments>
		<pubDate>Tue, 08 Sep 2009 18:23:58 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[TSQL Development]]></category>
		<category><![CDATA[SQLErrors]]></category>

		<guid isPermaLink="false">http://www.sqlserver007.com/?p=217</guid>
		<description><![CDATA[Today I stuck with an interesting problem of converting number data in Varchar fields to numeric datatypes. I have created the following sample data The data in the table contains Decimal and scientific values in varchar format as shown in the figure below. Now when I tried to convert the above values to numeric as [...]]]></description>
			<content:encoded><![CDATA[<p>Today I stuck with an interesting problem of converting number data in Varchar fields to numeric datatypes. I have created the following sample data</p>
<div id="attachment_218" class="wp-caption aligncenter" style="width: 362px"><img class="size-full wp-image-218" title="Create table SQL  script" src="http://www.sqlserver007.com/wp-content/uploads/2009/09/Numerictable_Creation.png" alt="Create table SQL  script" width="352" height="375" /><p class="wp-caption-text">Create table SQL  script</p></div>
<p>The data in the table contains Decimal and scientific values in varchar format as shown in the figure below.</p>
<p><img src="http://www.sqlserver007.com/wp-content/uploads/2009/09/Table_NumericData1.png" alt="Table_NumericData" title="Table_NumericData" width="164" height="117" class="aligncenter size-full wp-image-225" /></p>
<p>Now when I tried to convert the above values to numeric as below it returns only 3 rows but with the following message</p>
<div id="attachment_221" class="wp-caption aligncenter" style="width: 181px"><img src="http://www.sqlserver007.com/wp-content/uploads/2009/09/WrongSQL_numeric.png" alt="Wrong SQL" title="WrongSQL_numeric" width="171" height="157" class="size-full wp-image-221" /><p class="wp-caption-text">Wrong SQL</p></div>
<p></p>
<p><strong>Msg 8114, Level 16, State 5, Line 2<br />
Error converting data type varchar to numeric.</strong></p>
<p>The isnumeric does return 1 for all the 4 values in the table. I modified the query so that it initially converts to<br />
float and then converts to numeric and it works.<br />
<br />
<div id="attachment_222" class="wp-caption aligncenter" style="width: 319px"><img src="http://www.sqlserver007.com/wp-content/uploads/2009/09/CorrectSQL_numericFormat.png" alt="Correct SQL" title="CorrectSQL_numericFormat" width="309" height="102" class="size-full wp-image-222" /><p class="wp-caption-text">Correct SQL</p></div></p>
<p><img src="http://www.sqlserver007.com/wp-content/uploads/2009/09/numeric_ResultTable1.png" alt="numeric_ResultTable" title="numeric_ResultTable" width="277" height="114" class="aligncenter size-full wp-image-227" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sqlserver007.com/2009/09/08/error-converting-data-type-varchar-to-numeric/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value</title>
		<link>http://www.sqlserver007.com/2009/06/22/the-conversion-of-a-char-data-type-to-a-datetime-data-type-resulted-in-an-out-of-range-datetime-value/</link>
		<comments>http://www.sqlserver007.com/2009/06/22/the-conversion-of-a-char-data-type-to-a-datetime-data-type-resulted-in-an-out-of-range-datetime-value/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 11:53:02 +0000</pubDate>
		<dc:creator>Vivek</dc:creator>
				<category><![CDATA[TSQL Development]]></category>
		<category><![CDATA[SQLErrors]]></category>

		<guid isPermaLink="false">http://www.sqlserver007.com/?p=205</guid>
		<description><![CDATA[The Error Occurs when the input is date and the given day values are not in the range of the expected days for a given month(1-31) For eg. You cannot specify the date parameter as Feb 31 2009 since february only has 28 days in a non-Leap year and it throws the above error.]]></description>
			<content:encoded><![CDATA[<p>The Error Occurs when the input is date and the given day values are not in the range of the expected days for a given month(1-31)</p>
<p>For eg.</p>
<p>You cannot specify the date parameter as Feb 31 2009 since february only has 28 days in a non-Leap year and it throws the above error.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sqlserver007.com/2009/06/22/the-conversion-of-a-char-data-type-to-a-datetime-data-type-resulted-in-an-out-of-range-datetime-value/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
