Friday, April 17, 2009

MS SQL 2005: More on the underused OUTPUT clause

In a previous entry, I mentioned the sometimes under-used OUTPUT clause as an alternative to CF8's result.IDENTITYCOL. If you have used MS SQL for a while, you are no doubt aware of it already. But for those that are not, OUTPUT can be very useful. Especially when working with multiple records.

When manipulating sets of data, I often need to answer questions like "which records were updated?", "what were the original values, before the update?", "which records were was deleted?". The OUTPUT clause lets you do just that.

When using OUTPUT, two special prefixes are available: Inserted and Deleted. The Inserted prefix is used to obtain values that were added. Such as a newly inserted record, or the new value of updated records. The Deleted prefix is used to grab information about deleted records, or the original values of updated records.

Grabbing the new ids of multiple records
Say you are inserting multiple records into a table, and need to grab the ids of the new records. Simply add an OUTPUT clause and use the Inserted prefix, to grab the new ids. You can either return the values as a query, or insert them into another table:

Example


-- Create sample table
-- Use a table variable (no messy clean up)
DECLARE @Customer TABLE
(
CustomerID INT IDENTITY(1,1),
FirstName VARCHAR(50),
LastName VARCHAR(50)
)

--- Create a table for storing the new id's
DECLARE @NewRecords TABLE
(
InsertedCustomerID INT
)

--- A) Insert the new ids into a table variable
INSERT INTO @Customer ( FirstName, LastName )
OUTPUT Inserted.CustomerID INTO @NewRecords ( InsertedCustomerID )
SELECT 'Alan', 'Mercury' UNION ALL
SELECT 'Michelle', 'Dupree' UNION ALL
SELECT 'Josh', 'Echor' UNION ALL
SELECT 'Alan', 'Roberts'

--- Display the id's of the inserted records
SELECT InsertedCustomerID
FROM @NewRecords

--- B) Return the new ids as a resultset
INSERT INTO @Customer ( FirstName, LastName )
OUTPUT Inserted.CustomerID
SELECT 'Alan', 'Mercury' UNION ALL
SELECT 'Michelle', 'Dupree' UNION ALL
SELECT 'Josh', 'Echor' UNION ALL
SELECT 'Alan', 'Roberts'


Finding out which records changed
You can apply the same technique to UPDATE statements. But with updates, you can take advantage of both prefixes: using the Deleted prefix to grab the original values (before the update) and Inserted to grab the new values (after the update).



--- Change a few records
UPDATE @Customer
SET FirstName = 'Adam'
OUTPUT Deleted.CustomerID AS UpdatedCustomerID,
Deleted.FirstName AS OldFirstNameValue,
Inserted.FirstName AS NewFirstNameValue
WHERE FirstName = 'Alan'


Determing which records were deleted
Of course the same applies to DELETE statements. Just use the Deleted prefix to return information about the deleted records.


--- Delete some records randomly
DELETE FROM @Customer
OUTPUT Deleted.CustomerID AS DeletedCustomerID,
Deleted.FirstName AS DeletedFirstName,
Deleted.LastName AS DeletedLastName
WHERE LastName LIKE '%o%'


Just another tool to keep in mind when using 2005 ;)

...Read More

MS SQL 2005: The under-used OUTPUT clause

While not new, some of the nicer features first introduced with MS SQL 2005 are often overlooked. After spending time working with different, or older, databases I sometimes forget about them myself. One of the more useful features worth remembering is the OUTPUT clause.

If you are not familiar with it, OUTPUT clause allows you to retrieve information about records that were just inserted, updated or deleted. This information can be returned as resultset or even inserted into another table (or table variable). It is incredibly useful when working multiple records, but comes in handy in other situations as well.

result.IDENTITYCOL alternative
One example is with INSERT statements. While ColdFusion 8 introduced the much needed result attribute (which can return the ID of a newly inserted record) it has a few limitations. It only works for single record inserts, and also has a few quirks. The OUTPUT clause offers an interesting alternative to using CF 8's result.IDENTITYCOL value.

Take the simple insert below that adds a record into a table with an identity column. By adding an OUTPUT clause, and using the special Inserted prefix, you can access the id of the newly created record (or any other value in the record).

By default, OUTPUT returns the information as resultset. So you end up with a query containing the new record ID. Just as if you were using a SELECT statement instead. On the "upside", this seems to work consistently with the CF 8, MS SQL JDBC 1.0 and 1.2 drivers, unlike the result attribute. Unfortunately ... it did not work with the jtds driver. At least not in my tests. Still an interesting alternative to result.IDENTITYCOL.

Using OUTPUT


CREATE TABLE Customer
(
CustomerID INT IDENTITY(1,1),
FirstName VARCHAR(50),
LastName VARCHAR(50)
)

<cfquery name="addRecord" datasource="#dsn#">
INSERT INTO Customer ( FirstName, LastName )
OUTPUT Inserted.CustomerID
VALUES
(
<cfqueryparam value="Alan" cfsqltype="cf_sql_varchar"> ,
<cfqueryparam value="Mercury" cfsqltype="cf_sql_varchar">
)
</cfquery>

<cfdump var="#addRecord#" label="Show the new Record ID">


One of these days I will have chart out all of the options, the various issues with each, and see which one equates to the least headaches.

* Improving inserts, updates and deletes with OUTPUT

...Read More

SOT: jQuery Sparklines

I just came across this cool jQuery plugin for creating sparklines and thought I would pass it along for anyone else living under a jQuery rock like me.

http://omnipotent.net/jquery.sparkline/

...Read More

Tuesday, April 14, 2009

Concatenating values in SQL

A relatively common need is concatenating a bunch values in a query. While cfoutput with "group" is one option, there are also some elegant sql options. Ones that do not involve temp tables or descending into cursor psychosis. There are different reasons for each, but if you are not aware of the sql options, Barney Boisvert sums them up quite nicely in this recent post at houseoffusion.com:

http://www.houseoffusion.com/groups/cf-talk/thread.cfm/threadid:59194

...Read More

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Header image adapted from atomicjeep