Code Example: sample cursor, and try/catch block (MSSQL)

Here we have a simple cursor, in MSSQL.

DECLARE @objid INT

DECLARE @CR CURSOR
SET @CR = CURSOR FOR SELECT DISTINCT id FROM [table]

OPEN @CR
FETCH NEXT FROM @CR INTO @objid

WHILE @@FETCH_STATUS = 0
BEGIN

update [other_table] set [column] = value
where id = @objid

FETCH NEXT FROM @CR INTO @objid
END
CLOSE @CR
DEALLOCATE @CR

 

Using this you can do a lot of great jobs in MSSQL; it is very helpfully when you have to update/delete a teble with values from a set of rows where you have to take the last registered.

Also when an long update is running, it is more okay if you do this with an cursor. You can use inside of your cursora try catch block, that will manage a desaster, and will continue to do the job for the rest of the ads.

A try catch code in MSSQL:

 

BEGIN TRY
    insert into ad(id) values(121)
END TRY
BEGIN CATCH
    print ERROR_MESSAGE()
    print ERROR_SEVERITY()
END CATCH

This is very helpfully in many situations, a programmer knows this Cool

 


Posted by: admin
Posted on: 9/16/2009 at 2:11 PM
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (5) | Post RSSRSS comment feed
-->