Home

Advertisement

Customize
About this Journal
Current Month
 1234
567891011
12131415161718
19202122232425
2627282930
Apr. 20th, 2009 @ 10:58 am rode a 250 ninja
so you ever wonder what it's like to ride a 250 ninja? Me neither but
here's my experience with it:

 

Read more... )
About this Entry
Jan. 29th, 2009 @ 09:07 am SQL Output Clase - for those who DON'T Know

SQL Output Clause

Insert, update, and delete statements can have an output clause.

This can output cells from the impacted rows.  

Read more... )
About this Entry
Jan. 29th, 2009 @ 09:02 am SQL XML - for those who DON'T know

SQL XML

Sql 2005 supports xml natively. This allows for data structures to be stored in yet another way, and is occasionally very useful for building objects.


 

Read more... )

 

About this Entry
Jan. 29th, 2009 @ 08:45 am SQL try/catch/transaction - for those who DON'T know

Try Catch Throw, and Transactions

Sql 2005 introduced a better try/catch construct and the ability to re-throw the exception. Previously checking the @@error was really the only way to test for errors. This makes commiting/rolling back transactions a synch and still allows the option to bubble an error up to .net or whatever is calling a stored proc

 

Read more... )
About this Entry
Jan. 29th, 2009 @ 08:19 am SQL Pivot/Unpivot - for those who DON'T know

Pivot, Unpivot

Pivot and unpivot allow the selection of rows as columns and vice versa. This is mostly useful for reporting and often data-imports. Pivot rotates rows (values) into columns

 


 

Read more... )
About this Entry
Jan. 28th, 2009 @ 08:35 am SQL CTE Common table expressions - For those who DON'T know

Common Table Expression (CTE) now with 100% more recursion!

 

 

Common Table Expressions are pretty much a just in time view that can be used in a query or stored proc. The advantage over a view is the ability to use parameters to limit the dataset used.

 


 

Read more... )

 

About this Entry
Jan. 27th, 2009 @ 04:10 pm SQL Group By Where Having Select Distinct - for those who DON'T know

Group By, Where, Having, Select Distinct

Group By is possibly the least understood commonly used function of SQL. A typical use for group by will come from a query such as this one:

SELECT count([ProductID])

      ,[Name]

      ,[ProductNumber]

      ,[MakeFlag]

      ,[FinishedGoodsFlag]

      ,[Color]

      ,[DaysToManufacture]

 FROM Production.Product

Which returns an error:

Msg 8120, Level 16, State 1, Line 1

Column 'Production.Product.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

So a developer will end up doing something like this:

SELECT count([ProductID])

      ,[Name]

      ,[ProductNumber]

      ,[MakeFlag]

      ,[FinishedGoodsFlag]

      ,[Color]

      ,[DaysToManufacture]

 FROM Production.Product

group by [Name]

      ,[ProductNumber]

      ,[MakeFlag]

      ,[FinishedGoodsFlag]

      ,[Color]

      ,[DaysToManufacture]

Which doesn’t really provide any useful information.

A proper use for the group by clause is to specify on what to base the aggregate function (count, sum, avg, max, etc.). By saying “select count(productid)…. Group by daystomanufacture” the developer is requesting a listing of the count of products FOR EACH value in daystomanufacture.

 

Count(productid)

daystomanufacture

246

0

154

1

7

2

97

4

 

The where and having clauses can change these numbers. Where is used for pre-aggregation filtering, and Having is used for post-aggregation filtering. Consider these two queries

SELECT count([ProductID])

      ,[DaysToManufacture]

 FROM Production.Product

where daystomanufacture<2

group by

      [DaysToManufacture]

And

SELECT count([ProductID])

      ,[DaysToManufacture]

 FROM Production.Product

group by

      [DaysToManufacture]

having count(ProductID)>7

The first will return the rowset where DaysToManufacture, a field in the table, is less than 2. The second will return the rowset where the COUNT of productid, a calculated aggregate is >7

 

Select Distinct returns records that are not identical. THIS DOES NOT FIX PROBLEMS WITH INCORRECT CARTESIANS!

 

Select a, b from tblsomething

 

A

B

1

Alpha

1

Bravo

2

Delta

2

Delta

Select distinct a, b from tblsomething

 

A

B

1

Alpha

1

Bravo

2

Delta

About this Entry
Jan. 27th, 2009 @ 04:07 pm SQL joins - for those who DON'T know

Joins

Properly joining two tables or views is a bit of an artform. Incorrect but functioning joins cause hours of annoyance to developers, especially when they’re doing reporting and trying to figure out why their totals are 2x the expected results (usually a Cartesian because of multiple matches caused by not enough conditions in the join).

There are 4 (well 5) types of joins: Inner, left outer, right outer, full outer, and Inner with a different syntax (a leftover from older versions). Let’s take 2 tables, a, and b. Joined on column A.ID and B.AID

A.ID

1

2

3

4

5

6

 

B.AID

1

2

3

7

8

9

 

 

A inner join B will return everything in A and B where A.ID and B.AID are equal. Only records that match in both will be returned.

A.ID

B.AID

1

1

2

2

3

3

 

A left outer join B will return everything in A and only records in B where B.AID=A.AID and will return null for the B portion of the record where there is no match

A.ID

B.AID

1

1

2

2

3

3

4

Null

5

null

6

null

 

A right outer join B will return everything in B and only records in A where B.AID=A.AID and will return null for the A portion of the record where there is no match

A.ID

B.AID

1

1

2

2

3

3

Null

9

null

8

null

7

 

 

A full outer join B will return everything in A and B with nulls for no matches

 

A.ID

B.AID

1

1

2

2

3

3

4

Null

5

null

6

null

Null

9

null

8

null

7

 

 

 

Cartesians and Many-to-one or many-to-many joins

Joins which have multiple matches between the tables will return all combinations of the match

A.ID

1

2

3

4

5

6

 

B.AID

B.INFO

1

Hi

1

Hello

3

Guten Tag

4

Hola

4

Bonjour

9

Privet

 

A result of an inner join between these tables on A.ID=B.AID would look like this

A.ID

B.AID

B.INFO

1

1

Hi

1

1

Hello

3

3

Guten Tag

4

4

Hola

4

4

Bonjour

 

Inner join has 2 syntaxes:

select ... from a inner join b on a.ID=b.AID

and

select ... from a, b where a.ID=b.AID

these work the same way, but the older style (using the where) is much harder to quickly read to the developer (the conditions of the join are not next to the join, but instead in the where clause). Also, the outer joins don’t have a similar syntax, so you can end up with mixed syntax in the from clause. What an eyesore!


About this Entry
Jan. 27th, 2009 @ 04:06 pm SQL Views - for those who DON'T know

Views

Views help organize the logical structure of the database and reduce code clutter. They can also be indexed for faster search results (useful for improving performance)

A view is basically a query stored for use by other queries. For example to get products and some related info to them we can create this view.

 

 

create view dbo.ProductsCategories

as

select

      ProductID,

      prod.[Name] as ProductName,

      ProductNumber,

      subc.[Name] as SubCategoryName,

      prodc.[Name] as CategoryName

from Production.Product prod

      left outer join Production.ProductSubcategory subc

            on subc.ProductSubcategoryID=prod.ProductSubcategoryID

      left outer join Production.ProductCategory prodc

            on subc.ProductCategoryID=prodc.ProductCategoryID

 

Notice a couple things: with [Name] brackets are used to differentiate between a SQL keyword and a field. Prod, prodc, subc are aliases for tables used to reduce clutter and typing.

This view could be used as

select * from ProductsCategories

or more appropriately since “select * “ is a major no-no for sql (hurts performance, readability, and is just bad form)

SELECT ProductID

      ,ProductName

      ,ProductNumber

      ,SubCategoryName

      ,CategoryName

 FROM ProductsCategories

 

Also this view can be used in joins

SELECT p.ProductID, pc.ProductID from

Production.Product p

inner join ProductsCategories pc on p.ProductID=pc.ProductID

About this Entry
Jan. 27th, 2009 @ 04:05 pm SQL Stored Procedures - for those who DON'T know - parameters and output parameters

Stored Procedures

An absolute must for SQL development, stored procs allow you to keep data access code and logic outside of your web projects.

 

 

 

create proc dbo.SelectProductByIDorName

      @productid int,

      @name varchar(50)

as

Select

      ProductID,

      Name,

      ProductNumber,

      Color,

      ReorderPoint

from

      Product

where

      ProductID=@productid

      or [Name]=@name

here we create a stored procedure that returns a rowset of products that are matched on the parameters passed to it.

This can be called using

 

exec SelectProductByIDorName 1,''

or

 

SelectProductByIDorName 1,''

Or

DECLARE @RC int

DECLARE @productid int

DECLARE @name varchar(50)

select @productid=1, @name=''

 

EXECUTE @RC = [SelectProductByIDorName]

   @productid

 ,@name

 

Similar things can be done for insert, update, delete, and nearly anything else

Also, parameters for stored procs can go both ways, both input and output.

Input parameters are shown above, they are used to feed information to the procedure.

Output parameters can be used to return data from the procedure that is not in rowset format.

 

CREATE PROCEDURE dbo.spReturnAndOutputTest

    @OutTest int OUTPUT

AS

 SET @OutTest = 9

 RETURN 1

 

Calling this proc

 

declare @outtest int

exec spReturnAndOutputTest @outtest OUTPUT

select @outtest

 

Here we declared a variable to store the results from the stored procedure call. Called the proc passing it the variable, and selected the result

About this Entry
Jun. 5th, 2008 @ 08:42 am saw "Don't Mess With The Zohan"

saw a sneak preview of Zohan. 
it's surprisingly good (not the typical adam sandler role). recommend seeing it definately. It's a weird mix of Munich, West Side Story, Shaft, Little Nicky and something else that i can't put my finger on
it's a spoof about an israeli special forces dude that wants to move to america to cut hair. 
movie contains: 
-constant jokes at the expense of Humus ("a tasty middle eastern substance that looks like diarrhea")
-stereotypical palestinian cab drivers
-stereotypical everyone really (jewish electronics store, arab terrorist with 20 hot wives,etc.)
-entirely too much use of the definite article "the"
movie does not contain: 
-present tense conjugation of the verb "to be" namely "is", "am", etc. (i.e. "i go to store")

About this Entry
May. 14th, 2008 @ 09:26 pm rofl
К нам сегодня приходил, межпланетный педофил. Малолетних организмов он с собою приносил
-Сергей Лукьяненко
About this Entry
Apr. 6th, 2008 @ 06:00 pm (no subject)
interesting problem:
a chicken and a half lays an egg and a half in a day and a half.
how many eggs can one chicken lay in 3 days?

and another
a builder and a half builds a house and a half in a year and a half using a tool and a half
how many houses can one builder build in 9 years?


/stolen from some sql server magazine
About this Entry
Apr. 6th, 2008 @ 05:20 pm camden is burning
looks like something about 10 blocks east of the ben franklin. also the big black cloud of smoke can be seen for miles... firetrucks from philly heading over the bridge to help...
anyone know wtf is going on?
About this Entry
Mar. 10th, 2008 @ 09:22 pm flooding in new hope...
 took some photos in new hope this weekend...
 http://public.fotki.com/ZenithPhotography/1/nature-photography/new-hope-pa-392008/
About this Entry
Mar. 1st, 2008 @ 10:23 am to download

 Billy`s band  (kupchino stolica mira)
Marksheider Kunst

About this Entry
Jan. 16th, 2008 @ 11:03 pm when rappers find powerpoint
http://madhattannights.com/when-rappers-get-ahold-of-powerpoint/
About this Entry
Jan. 6th, 2008 @ 08:35 pm стикер-мания
обшался с одним мужиком. будем условна называть его Вася. Вася из Питера.
Вася апсалютно нармальный чувак практически без замашек и хрени всякой, кроме одной весши. Абсолутный стикер-маньяк. (может ето как-то падругому называетса, но лучше названия придумать нимагу). Болезнь заклучается в следуесшем: если батинки не "Прада" или не "Лакосте" нииизачот. Если курта не "барбери" (заметьте произношение) полный атстой. если исшо ченить "не фирма" просто ниибет.
Еше прекол. Вася в полном ахуе от джинс фирмы Левиз (Levis). Гаварит что афигенные весчи и можно носить наравне с чем угодно.
Например, ахрененно дорогие шузы (фирма ниизвестна) красивые, уникальные, но без этикетки (потому что это маленькая фирма в италии) то это можно сравнить с кирзовыми сапагами. А какие-то абсолютно стандартные кеды (на уровне Chuck Taylor All Stars, "Bobos") но с кракадильчегом лакоста, то ето аффигеть и дайгте исчо.

Вот я думаю, ето шас национальная/классовая черта или ето один экземпляр? или может я так как мне шмотки абсалютно пофигу просто что-то пропустил?
About this Entry
Dec. 28th, 2007 @ 12:36 pm woot edu v piter
26 fevralya - 4 marta :)
About this Entry
Dec. 14th, 2007 @ 10:33 pm got orange box
tf2 is funny. all the characters look goofy as hell. it's like playing a cartoon
About this Entry