Search This Blog

Monday, August 19, 2013

Something useful for myself

Replacing a string in MS SQL.

REPLACE(OriginalField, "OldString", "NewString")

SELECT REPLACE(LastName, "Smith", "OriginalSmith")

This would change all occurrences of Smith in the LastName field to OriginalSmith. Smith becomes OriginalSmith, O'Smith becomes O'OriginalSmith, smithey becomes OriginalSmithey, and so forth. Microsoft has this on their site, but sometimes their terminology is too technical when looking for a quick answer.

Wednesday, August 7, 2013

Cursors in MS SQL

I'm always forgetting now to do a simple cursor in MS SQL, so here is the basic structure

DECLARE @field1 VARCHAR(10)
DECLARE @field2 VARCHAR(10)

DECLARE name_cursor CURSOR
FOR
SELECT field1, field2 FROM table WHERE this = 'that'

OPEN name_cursor

FETCH NEXT FROM name_cursor INTO @field1, @field2

WHILE @@FETCH_STATUS = 0
BEGIN
--DO WORK HERE
FETCH NEXT FROM name_cursor INTO @field1, @field2
END

CLOSE name_cursor
DEALLOCATE name_cursor

An alternate would be
WHILE @@FETCH_STATUS <> -1 -- -1 indicates beyond result set
BEGIN
IF @@FETCH_STATUS <> -2 -- -2 indicates row is missing
BEGIN
--DO WORK
FETCH NEXT
END
END