Monday, September 24, 2007

SQL 2005 : SQL 2005 - TSQL Enhancements

 

SQL 2005 - TSQL Enhancements

--------------------------------
--SQL 2005 - TSQL Enhancements--
--------------------------------
------------------
--Error Handling--
------------------
--In SQL 2000, you had to check and handle @@Error after each statement
--In SQL 2005, we have TRY, CATCH (but no FINALLY)
CREATE PROCEDURE [dbo].[ErrorProc]
AS
DECLARE @Value int;
BEGIN TRY
SELECT @Value = 200;
PRINT 'Value set to 200';
--Force Error
SELECT @Value = @value / 0;
PRINT 'Value divided by 0';
END TRY
BEGIN CATCH
PRINT 'In Error Handler'
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_MESSAGE() AS ErrorMessage,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_SEVERITY() AS ErrorSeverity,
@Value
END CATCH
GO
EXEC ErrorProc
------------------------------------------------------
--New Datatype size for varchar, nvarchar, varbinary--
------------------------------------------------------
--It is now possible to use (MAX) as a datasize for varchar, nvarchar, varbinary
--Eg. varchar(MAX), nvarchar(MAX), varbinary(MAX)
--These *replace* text, ntext and image datatypes, although they remain fo backwards
--compatibility
--
--These can be used as local variable
DECLARE @MaxNvarchar nvarchar(MAX)
SELECT @MaxNvarchar = REPLICATE('This is big data ', 250)
SELECT @MaxNvarchar = @MaxNvarchar + '*** Steve *** '
SELECT @MaxNvarchar = @MaxNvarchar + REPLICATE('And lots more text ',200)
SELECT @MaxNvarchar = @MaxNvarchar + REPLICATE('And lots more text ',200)
SELECT @MaxNvarchar = @MaxNvarchar + '*** End ***'
SELECT
@MaxNvarchar AS [Data]
,DATALENGTH(@MaxNvarchar) AS [DataLength]
,LEN(@MaxNvarchar) AS [Len]
,CHARINDEX('End', @MaxNvarchar) AS [EndPos]
GO
--Becareful though. Not all functions operate over more than 8000 characters
DECLARE @MaxNvarchar nvarchar(MAX)
SELECT @MaxNvarchar = REPLICATE('This is big data ', 250)
SELECT @MaxNvarchar = @MaxNvarchar + '*** Steve *** '
SELECT @MaxNvarchar = @MaxNvarchar + REPLICATE('And lots more text ',400)
SELECT @MaxNvarchar = @MaxNvarchar + '*** End ***'
SELECT
@MaxNvarchar AS [Data]
,DATALENGTH(@MaxNvarchar) AS [DataLength]
,LEN(@MaxNvarchar) AS [Len]
,CHARINDEX('End', @MaxNvarchar) AS [EndPos]
--Varbinary(MAX) allows binary data upt o 2Gb
DECLARE @MaxVarBinary varbinary(MAX)
--XML datatype - more on this later
DECLARE @xmldata xml
----------------------------
--Common Table Expressions--
----------------------------
--Show Tables
select * from emp;
with emph(id, name, mgrid, lvl, rootmgrid)
as
(
--anchor member
select id, name, mgr_id, 0, id
from emp
where mgr_id IS NULL
union all
--RECURSIVE STEP
select e.id, e.name, e.mgr_id, lvl + 1, eh.rootmgrid
from emp e
join emph eh
on eh.id = e.mgr_id
)
select * from emph where rootmgrid = 1
SELECT * FROM emp
---------------------
--RANKING FUNCTIONS--
---------------------
--Row Number--
SELECT
[name]
,[age]
,ROW_NUMBER() OVER(ORDER BY [name]) AS namerownumber
,ROW_NUMBER() OVER(ORDER BY [age]) AS agerownumber
FROM
emp
ORDER BY
[name];
--Paging--
WITH myemp AS
(
SELECT
[name]
,[age]
,ROW_NUMBER() OVER(ORDER BY [name]) AS namerownumber
FROM
emp
)
SELECT
*
FROM
myemp
WHERE
namerownumber BETWEEN 4 AND 6
--Ranking--
with emprank
as
(
select
row_number() over(order by id) AS [Row],
rank() over (order by sales desc) AS [Rank],
rank() over (partition by country order by sales desc) AS [RankByCountry],
dense_rank() over (order by sales desc) AS [DenseRank],
ntile(5) over (order by sales desc) AS [FifthPercentile],
name,
country,
age,
sales
from
emp
)
select * from emprank
----------------------------------------------
--Replacing the need for cursors/while loops--
----------------------------------------------
--This example shows the creation of running total sales
--The main purpose, is to demonstrate how much easier the code is with 2005
--In 2000, you would have to insert into a temp table with an identity value
--Then create a cursor over the temporary table, iterating over each row
--updating the new total, to a running total value of sales
drop table #totals
select row_number() over (order by id) rn,
name, country, sales into #totals
from emp;
with rt (rn, name, country, sales, runtot)
as
(
select rn, name, country, sales, sales
from #totals
where rn = 1
union all
select t.rn, t.name, t.country, t.sales, t.sales + rt.runtot
from #totals t
join rt on t.rn = rt.rn + 1
)
select * from rt
drop table #totals
------------------
--Pivot function--
------------------
select * from sales
pivot( sum(total) for period in ([Q1], [Q2], [Q3], [Q4])) p
----------------------------------------------------
--Output affected rows during update/delete/insert--
----------------------------------------------------
--drop procedure updSales
create procedure updSales
as
--Create table to store modified rows
DECLARE @tab TABLE (id int, name varchar(15), oldsales int, newsales int)
BEGIN TRAN
--Modify some rows
UPDATE
emp
SET
sales = sales + 50
OUTPUT
inserted.id,
inserted.name,
deleted.sales,
inserted.sales
into @tab
WHERE
sales >= 400
--Rollback transaction, as test proc and don't really want to alter db
ROLLBACK TRAN
--Return affected rows
select * from @tab
GO
SELECT * FROM emp
EXEC updSales
GO
-----------
--New TOP--
-----------
SELECT
*
FROM
Sales
DECLARE @rows int;
SELECT @rows = 3;
SELECT TOP(@rows)
*
FROM
Sales
--It is also possible to use this on INSERT/UPDATE/DELETE

Published Saturday, February 11, 2006 3:17 PM by sbates

Filed under: SQL 2005 - Code samples, SQL 2005 - What's New

Source: SQL 2005 : SQL 2005 - TSQL Enhancements

Sql Server. Get space used (sp_SpaceUsed) for all tables in database - Author Nigel Rivett

 

This calls sp_SpaceUsed for each table in a database and accumulates the data in a temp table. Output the data to a file or table to monitor the database.

Source: Sql Server. Get space used (sp_SpaceUsed) for all tables in database - Author Nigel Rivett

Sql Server 2005. Save and display query plans and statements for all spids - Author Nigel Rivett

 

When you run the sp s_GetQueryPlans it will create a file of every statement (or a single spid) that is running on the system. It will also create other files of associated query plans. Double click on the files and they will open in management studio showing the query or query plan diagram. This is useful for diagnosing problems on a system.

Source: Sql Server 2005. Save and display query plans and statements for all spids - Author Nigel Rivett

Monday, September 17, 2007

LINQ to SQL Debug Visualizer - ScottGu's Blog

 

The LINQ to SQL Debug Visualizer isn't built-in to VS 2008 - instead it is an add-in that you need to download to use.  You can download a copy of it here.

Source: LINQ to SQL Debug Visualizer - ScottGu's Blog

Thursday, September 13, 2007

SQLServerCentral.com Script Library

Scripts from the maker of Sql Spy. 

Displays Identity Column Values
By: Robert Vallee - Posted: 10/21/2001
Script Rating (3.71)   Total number of votes [7]
Displays identity column values, number of rows in the table, and the difference between the two. The difference can indicate the amount of deletions that could be going on. ...

Display Identity Values and Other Info
By: Robert Vallee - Posted: 09/06/2001
Script Rating (3)   Total number of votes [6]
Displays identity values, number of rows in the table, and the difference between the two. The difference can indicate the amount of deletions that could be going on. ...

Display Stored Procedure Parameters
By: Robert Vallee - Posted: 09/04/2001
Script Rating (4.41)   Total number of votes [17]
Display any stored procedures using input and output parameters. I took the view, PARAMETERS that ships with SQL 2000 and cleaned it up a bit. ...

Output Language Date Settings
By: Robert Vallee - Posted: 09/04/2001
Script Rating (1)   Total number of votes [1]
Display language/date settings for your SQL Server. ...

hx_Windows_Logins
By: Robert Vallee - Posted: 08/22/2001
Script Rating (3.75)   Total number of votes [4]
Display only windows logins for SQL Server ...

hx_ShowIdentityColumns
By: Robert Vallee - Posted: 08/22/2001
Script Rating (3.43)   Total number of votes [7]
List out all columns that are set as Identity columns in the database ...

hx_ShowFixedDriveSpace
By: Robert Vallee - Posted: 08/22/2001
Script Rating (2.4)   Total number of votes [5]
Very simple, how much space is free on the hard drives of the SQL Server you are connected to. ...

hx_OLEDBproviders
By: Robert Vallee - Posted: 08/22/2001
Script Rating (2.75)   Total number of votes [4]
Get OLE Providers info I have found this useful in tracking down application driver/connection issues. I only had to use it 2 times. But it did help ...

hx_JobSchedules
By: Robert Vallee - Posted: 08/22/2001
Script Rating (3.89)   Total number of votes [9]
Displays Job Schedules info if any ...

hx_IndexInformation
By: Robert Vallee - Posted: 08/22/2001
Script Rating (4)   Total number of votes [4]
Displays Index Info for whatever database it is run against ...

hx_DTSPackageDetails
By: Robert Vallee - Posted: 08/22/2001
Script Rating (2.5)   Total number of votes [2]
Displays DTS Package info if any ...

hx_dbMaintancePlans
By: Robert Vallee - Posted: 08/22/2001
Script Rating (2.5)   Total number of votes [2]
Displays Maintance plan history if any. I used distinct to filter out and return only what is relevent to what I need. You may not wish this for your purposes. Feel free to make changes ...

hx_DatabaseProperties
By: Robert Vallee - Posted: 08/22/2001
Script Rating (3)   Total number of votes [5]
Displays database properties. Was this the best way of doing it? Probably not, but it works. ...

hx_ConfigurationOptionReference
By: Robert Vallee - Posted: 08/22/2001
Script Rating (4)   Total number of votes [4]
Displays Configuration option references and current set values. ...

Optimize Character Field Usage
By: Robert Vallee - Posted: 08/10/2001
Script Rating (4.48)   Total number of votes [21]
This stored procedure was designed to scan all your character based columns in a particular database and show the minimum, maximum and average data length. As well as give an efficiency rating of the data stored. Input: None Output: Table...

Contribute a Script.

SQLServerCentral.com Script Library

SQL SPY - Open Source Amazing SQL Monitoring & Analysis

 This is one of the best tools I have seen in awhile.

Be sure to run sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_configure 'Ole Automation Procedures', 1; GO RECONFIGURE; GO

to access certain features.  The biography and live monitoring features are a must see.

Project SQL SPY 5.2 is out! This version of SQL SPY fully supports SQL Server 2005 and has many new features exclusively for SQL 2005.
SQL SPY was designed as a tool to display, monitor and report on valuable SQL Server information.

SQL SPY

Exporting Subreports from SQL Reporting Services

 

This question that has come up a few times on the project on which I am currently working.

‘How to ensure that Sub Report data in Reporting Services is included when exporting to XML and CSV formats?’

This is not the default behaviour of RS but luckily the answer is very simple.

  1. Right-click on your sub report and select properties.
  2. Note down the sub report name in the Name: field of the General Tab.
  3. Go to the Data Output Tab and type in the same name into the Element name: field.
  4. Ensure that the Output: radio button is set to Yes. Setting it to Auto doesn’t appear to work.

David Francis Blog

Sunday, September 09, 2007

MSFT Financial Analyst Meeting: Ray Ozzie

 

Ray talks about the Layers Microsoft is investing in:

GCF <--  CIS <-- LIVE <-- YOU

And the best way I've found to do this is to basically step through the architecture of the services platform and the nature of the solutions that'll take advantage of that platform. So at the bottom there, the first and lowest layer of the services platform are something we refer to as our Global Foundation Services. This is a physical layer of our services infrastructure that includes our datacenters, the racks of computers and disks that are inside those datacenters, the network that connects them to the Internet, and the people who build and operate these datacenters and maintain them and monitor the activities that are going on within them.

The datacenters are of massive scale. There's a number of them. They're built with commodity components, and that's how you get the cost down, and they achieve reliability through redundancy, not the fail-safe nature of any given component within the datacenter. Our expansion continues at this layer around the world. Next week we're going to be breaking ground in San Antonio on a fairly big datacenter, and our deployed servers and infrastructure has more than doubled over the course of the past year, and we will keep investing.

The next layer above that is our cloud infrastructure services layer. And this is the most fundamental software level of the services infrastructure. You can think of this as a utility computing fabric upon which all of our online services run. You know, among other services, this fabric has an efficient and isolated virtualized computation layer. It has application frameworks that support a variety of app models that are designed for horizontal scaling. And it has infrastructure that manages the automatic deployment and load balancing and performance optimization of the apps that it's managing running on its infrastructure.

It also supports several types of horizontally scalable storage types like files and database and searchable storage that are needed for different types of apps that you put onto this platform. And of course, you know, another key element is networking services, where to efficiently serve up apps and content to Internet users worldwide in a very low-latency and efficient manner.

The next layer up from there is something that I refer to as the Live platform services layer. And these are services that are designed specifically to serve the needs of apps, of our apps predominately, that target individuals and very small businesses, unmanaged users. These are generally ad-monetized applications, and because of that, there's synergy in sharing data and features among the apps at this level. And so they all share many, many of these services.

These are services like identity services, contact lists -- this is the layer where our social graph of your relationships lives, your presence and rendezvous, communication services. Perhaps most importantly, our advertising platform infrastructure lives at this level.

So whether it's hosting our Live offerings for individuals or our service-based offerings that are more targeted for enterprises, or apps that our partners or customers will provide -- this platform will ultimately be used by and will benefit all of the audiences that we as Microsoft serve, because each audience is undergoing some transformation that's relevant to them, from software-based solutions to software plus services, or services alone.

Source: MSFT Financial Analyst Meeting: Ray Ozzie

Why did Microsoft give us the Ribbon X?

 

The one thing I disliked the most about Office 2007 was the Ribbon.  It halts productivity for awhile (where did the format menu go? Oh it's Home now!) and screws with my head by not showing the menu I was shortcutting to... (Alt E - F - R?)

Not to mention the Jewel in the corner that hides the preferences menus, and important things like File - Save as.

The good news is you can download free (and $15) tools that recreate the good old file-edit menus that were in Office 2003.  The bad news is you have to download them - they should just be an option to check off in the system.

So why the Ribbon?

There are several reasons why Microsoft put ribbon in office. The most apparent one is target group. What is ribbon anyway? It's a toolstrip with tabs and really big icons. The reason why Microsoft decided to build office' user interface with it (the way I see it) is to make it easier for average secretary for whom computer is voodoo to use it. Instead of menus hiding option everything is right in front of her eyes, labeled, and with big shiny icons. That certainly makes it easier for starters to use it.

For advanced users however result is opposite. Advanced users do most of their work with keyboard shortcuts, and don't care about big icons and descriptive labels under them. What they rather care about is: this big thing on top of my screen eats up lot of space on my monitor. This is especially important in tools where you want to have multiple windows open at once, and every pixel is worth gold.

There's a reason why Microsoft didn't put ribbon in VS 2008, and (again, the way I see it) that is exactly this: different target group. Visual Studio is targeted for advanced users who don't care about big icons and who most of the time use keyboard shortcuts.

Source: Krzysztof Koźmic's blog - powered by FeedBurner

Thursday, September 06, 2007

Consuming the Reporting Services web service inside SSIS « The Furnace

 

I had a request to go into more detail as to an implementation of the ReportService web service inside SSIS.  I decided I’d take a crack at it.

Taking a snapshot of a report after a successful ETL load is a common task.  You could automate this task into the ETL load by consuming the Reporting Services web service and calling the UpdateReportExecutionSnapshot method and invoking Reporting Service to take a snapshot.  This could then be a catalyst for subsequent subscriptions for users who have asked to be notified when a new version of a report is ready.

Consuming the Reporting Services web service inside SSIS « The Furnace

Wednesday, September 05, 2007

Open XML Comes Up Short for ISO Standardization, Heads to 2008 Showdown

Microsoft lost the first round of trying to make Office 2007 XML an ISO Standard, which could hinder progress in government markets and the ability to tick off the ISO standard checkbox on an RFP. 

Microsoft has failed in its bid to fast track its Open XML document formats as ISO standards, thanks to a drubbing in the first round of the standardization process. Now, the software giant must respond to a litany of complaints and negative comments before it can resubmit the formats for standardization in early 2008.

Source: Open XML Comes Up Short for ISO Standardization, Heads to 2008 Showdown

Brian Jones has the positive spin - that over 9 separate apps currently use the Open XML format.

His comments tell a different story though.

Is RDL a standard yet?  I thought DOC & XLS (BIFF) were standards?  What am I missing here? 

Wasn't it easy enough to manipulate the binary code in Office 2003 documents?  This XML stuff is useless and bloated anyway....