Posts

Showing posts from 2012

Cursor Basics

When I started doing T-SQL, I remember Cursors being demonized and is said to be Evil by most of my colleagues, this made me shun away from using or even trying to understand how it works. Finally, in one of the interviews  I was asked how would you retrieve hundred or maybe thousand records and iterate on each while validating each row and doing insert if a row is valid?  My quick answer was to simply create a Table variable containing all the columns needed, plus an indexer column, do a INSERT INTO SELECT statement and also use  the Row_Number() Over syntax. After inserting all the records to the Table variable I now iterate on each row by doing a while loop and declaring an counter and making increments as it goes to the loop, and using the incremented value as where clause in the select statement. This is how the code would look like.. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 DECLARE @TempTable Ta...

SQL JOIN's revisited.

Yesterday I was asked what's the difference between UNION and UNION ALL , it made me think, I've been writing Stored Procedures for SQL Server for quite some time now. But almost always forget what what the difference between the two. It's time to reinforce it by writing it down through this blog. UNION  is used to combine result-sets of two or more SELECT statements,  the difference is really simple in UNION it only joins distinct values, meaning if there are duplicates it wont show it from the result-set, that's where ALL keyword is used when you want to include the duplicates in return. Union Syntax: SELECT ProductId FROM Products UNION SELECT  ProductId FROM Orders This will return unique  ProductId from Products and Orders Table combined and will ignore duplicates. Up Next differences between INNER JOIN, OUTER JOIN , LEFT and RIGHT JOIN and let's not forget CROSS JOIN CROSS JOIN Using cross join multiplies your rows from the first table to t...