Thursday, April 19, 2007

IF...ELSE Blocks

If Else Blocks are incredibly simple and can be rather helpful at times. This is the general syntax.

IF [Boolean Expression]
BEGIN
Print 'in if'
END
ELSE
IF
[Boolean Expression]
BEGIN
PRINT 'in else'
END

Wednesday, April 18, 2007

Cursors

You need a variable to hold the cursor value each time, so declare that first. Afterwards, we declare the cursor and set a one column returning select statement. These are teh values we will curse through... after this we'll do a couple things that assure the list of things we're cursing through hasn't ended, then we'll get into contents of what happens at each itteration, and then we'll wrap up by deallocating the cursor.


DECLARE @AuthorID char(11)

DECLARE c1 CURSOR FOR
SELECT au_id
FROM authors

OPEN c1


FETCH NEXT FROM c1
INTO @AuthorID


WHILE @@FETCH_STATUS = 0
BEGIN

PRINT @AuthorID

FETCH NEXT FROM c1
INTO @AuthorID
END

CLOSE c1
DEALLOCATE c1


And that's the gist of it. Source is here.

Assigning Variables With Select

declare @tablename varchar(100)
select @tableName = (select distinct TableName from aTable)

select @tablename