@@rowcount and print

by Allan Svelmøe Hansen June 07, 2010 19:45

Using @@rowcount is nice at times to get the number of rows affected by the last SQL statement. However sometimes you get an unexpected result.
One such situation is with the print statement which is often used as debugging statement in a query.
If looking at the SQL statement:
SELECT 1
UNION
SELECT 
2
SELECT @@ROWCOUNT
  


Then the @@rowcount naturally will return the value 2.
However if we insert a print statement just before the rowcount like this:

SELECT 1
UNION
SELECT 
2
PRINT 
'test'
SELECT @@ROWCOUNT
  

Rowcount now suddenly is 0.

That means the print statement changes the rowcount despite it being just a print to the console window.
Something to be aware of if relying on @@rowcount.

Bookmark and Share DotnetKicks dotnetshoutout

The MERGE syntax - syntax and performance

by Allan Svelmøe Hansen May 21, 2010 15:40

Normally when you have rows from one table you want to move over into the other, you'll have to run both an update query to get your existing rows updated with the new values and insert query to get new rows over to your target. That means you have to write two queries. With the merge, you only need one as it performs both the update and the insert.
So let's take a look at it.

First, I'll create 2 tables with dummy data; a tblSource and a tblTarget.
The scripts for creating the tables and data can be found here merge_setup_20100521.sql (3.58 kb), but basically it's just a target and source table with an ID, ValA, ValB and ValC with a clustered index on ID and some dummy data.
So to do the update/insert it would look like this:
UPDATE MyTarget SET 
   
MyTarget.ValA MySource.ValA

   
MyTarget.ValB MySource.ValB

   
MyTarget.ValC 
MySource.ValC 
FROM dbo.tblTargetInUp AS 
MyTarget  
INNER JOIN dbo.tblSourceInUp AS MySource ON MyTarget.ID 
MySource.ID 

INSERT INTO 
dbo.tblTargetInUp 
SELECT IDValAValB
ValC 
FROM dbo.tblSourceInUp AS 
MySource  
WHERE NOT EXISTS (SELECT FROM dbo.tblTargetInUp AS MyTarget WHERE MyTarget.ID MySource.ID
)  
 

If we look at the execution plan, I get an estimated cost of 9.1754 for the update and 2.48725 for the insert, meaning a combined cost of 11.66265 for 33.333 rows updated and 33.3334 rows inserted, into a target of 66.666 rows.

Now do remember, the estimated cost is just a number for how the query runs in my environment, it can't be taken as a direct number and transferred to another system - I'm only interested in the relative comparison with the merge. More data, more indexes, more variations will all affect the actual numbers. Also if looking at the execution plan, it is clear it is two queries we fire, meaning that all the overhead which goes into running one query will be doubled for this. But it was how you'd have to do merges in the past.

Now, with the merge syntax we can do it like this:
MERGE dbo.TblTargetMerge AS MyTarget USING 
(   
   
SELECT FROM dbo.TblSourceMerge AS 
TS 
AS 
MySource 
ON MyTarget.ID 
MySource.ID 
WHEN MATCHED 
THEN  
   UPDATE SET 
       
MyTarget.ValA MySource.ValA

       
MyTarget.ValB MySource.ValB

       
MyTarget.ValC 
MySource.ValC 
WHEN NOT MATCHED 
THEN 
   INSERT  
   
(IDValAValBValC

   
VALUES 
   
(MySource.IDMySource.ValAMySource.ValBMySource.ValC

  

Note that the syntax takes both the update and insert in the WHEN MATCHED and WHEN NOT MATCHED.
For the complete overview over the syntax, I'll refer you to the documentation by microsoft: MERGE (Transact-SQL).
But basically – you MERGE into a table using a source, and then define the ON clause (as you would a join), and then specify the WHEN MATCHED and the WHEN NOT MATCHED clauses.

One thing I'll expand on myself though, is the OUTPUT clause which can also be coupled on to the merge. I mentioned the OUTPUT clause myself recently.
The important thing is that you can couple the $action to the output clause and get information about whether you merged the data or you inserted the data, meaning whether the row was matched or not matched.
Like this:

MERGE dbo.TblTargetMerge AS MyTarget USING 
<...snipped FOR being brief...

OUTPUT $ACTION
rest_of_select_here 
;  
  

Nifty.
Anyways - once we've build this query, we can look at the execution plan, and here we clearly see it is handled as one query.
And in my case, the estimated cost is 8.407 for the same number of rows as above, meaning we’ve saved about 27.9% just by changing syntax.

Now, this structure I used to compare is very simple - with a simple matching of ID to ID and then just insert/overwrite everything so the actual result may vary (naturally), however the merge syntax does appear to be faster and with the added bonus of keeping the query combined into one syntax rather than divided into two different queries.
 
I must admit, I do like the merge syntax myself once I learned to read and write them.

Bookmark and Share DotnetKicks dotnetshoutout

A STR issue

by Allan Svelmøe Hansen May 20, 2010 17:49

I've seen many uses, and some misuses, of the STR function over time.

One of the more "easy to spot problems" is that the STR function returns char datatype, meaning it'll pad the result with spaces and people need to trim the result.

Today I saw an even worse issue. The STR function takes a float argument. This means if you feed it a string (yes, I've seen it done) it will implicit convert that string to a float if it can. That in itself can cause an error, but even worse, it can cause a difficult to find bug.
Suppose you have STR('0001') and run that, you'll after trimming end up with the result of '1'. Why?
Because '0001' is converted to a float, which - as we all know - is 1, which then will be cast to a string.

Bookmark and Share DotnetKicks dotnetshoutout

Tags: , , ,

SQL

The OUTPUT clause

by Allan Svelmøe Hansen March 20, 2010 12:25

The output clause is a really nifty thing in SQL Server 2008, which provides you access to the same "inserted" and "deleted" tables you get access to via triggers, but from within the same query.
To illustrate, suppose we have a table:

CREATE TABLE [dbo].[OutputEx]
   
[Key] [int] IDENTITY(1,1) NOT NULL, 
   
[Value] [nchar](10) NULL, 
   
[SecondValue] [datetime2](7) NULL, 
 
CONSTRAINT [PK_OutputEx] PRIMARY KEY CLUSTERED  

   
[Key] ASC 
)WITH (PAD_INDEX  = OFFSTATISTICS_NORECOMPUTE  = OFFIGNORE_DUP_KEY = OFF
ALLOW_ROW_LOCKS  
= ON,
ALLOW_PAGE_LOCKS  = ONON [PRIMARY] 
ON [PRIMARY] 

GO 

ALTER TABLE [dbo].[OutputEx] ADD  CONSTRAINT [DF_OutputEx_SecondValue]  DEFAULT (GETDATE()) FOR [SecondValue] 

This is a table which has an identity column in [Key] and a datetime value field in SecondValue2 which defaults to the current date (GETDATE())

Now, if I insert a [Value] into this table SQL Server will automatically insert the identity value and the current date SecondValue, but if I wanted to get these automated values out, I would have had to select them out manually afterwards.
This might not seem like much of a problem given these two values (Identity and date) however it might be much more complex constraints and default values.

So what I can do is use the OUTPUT clause like this:

INSERT INTO OutputEx Value)
OUTPUT inserted.[key]inserted.secondvalue         
VALUES  'a')  
 
This will provide me with a result of the identity value inserted into [key] and the date value inserted into SecondValue.
I can use this result in an outer query by nesting the insert in a sub-query, or I can insert it into another table directly like this:

DECLARE @T TABLE(ID INT[Date] DATETIME2)

INSERT INTO OutputEx Value)
OUTPUT inserted.[key]inserted.secondvalue  INTO @T
VALUES  'a')
 

 
My table variable @T will now hold the values inserted
This also works with the "deleted" table instead of the inserted and thus both in insert/update and deleted queries.
It is a useful technique.

Bookmark and Share DotnetKicks dotnetshoutout

Aggregated functions and CASE

by Allan Svelmøe Hansen February 03, 2010 13:11

I was stuck with a problem at work where I had a very complex query pulling data out of some tables, some XML and what not, and a lot of data manipulating in the query to be able to easier populate a DataWarehouse.
I then had to expand this query and pull some extra Boolean information out, which were based on a logical comparison of two strings, which I would normal do with a CASE like CASE string1 = string2 THEN 1.

However because I had a GROUP BY clause, I could not simply do this, because the columns the strings were taken from was not in the group clause and I didn’t want them there.
So I found out that you can actually put an aggregated function around the case using the following syntax:

SELECT 
<GroupByFields
>,
MAX
(
    
CASE 
        
WHEN <NonGroupField=  'some value' THEN 
1
        
ELSE 
0
    
END
)
FROM <TABLE
>
GROUP BY <GroupByFields

 

This saved me from using a common table expression or two more, and kept things simple. In essense this allows you to make conditional SUM and similar using this technique.
Just more evidence that a lot is possible in SQL, and just trying something often reveals interesting results.

Bookmark and Share DotnetKicks dotnetshoutout

Powered by BlogEngine.NET 1.6.1.0
Theme by Mads Kristensen | Modified by Mooglegiant

About:
Allan Svelmøe Hansen

My real name is Allan Svelmøe Hansen.
I live in Denmark, where I work as a developer for hedal:kruse:brohus using SQL Server and the .NET framework since 2004.
My primary fields of expertise is back-end data integration, database design and optimization.


       View Allan Svelmøe Hansen's profile on LinkedIn     

Disclaimer

The opinions expressed herein are my own personal opinions and thoughts and does not represent my employers view in any way, nor are my results guaranteed for all situations.
Content is presented "as is", with no warranty.