Tuesday, November 10, 2009

Commands by Example in T-SQL

1. T-SQL - declare/select/if...else/exec

declare @user varchar(32)
select @user = '${userLogin}'

declare @groupName varchar(32)
select @groupName = 'xxx'

declare @fullName varchar(64)
select @fullName = xxx from xxx

declare @found int
select @found = 0
select @found = 1 from xxx

if(@found=0)
begin
print "--adding user %1! = %2! --", @user, @fullName
declare @id xxx
exec xxx @table_name='xxx', @nr=1, @next_id=@id output
insert xxx values (@id, @fullName, @groupName)
end

2. while/if/else etc
declare @hldQuantity int
select @hldQuantity = 0
declare @buysell int
declare @execQuantity int
declare @execId int
declare @nextId int
select @nextId = min(exec_id) from exec,order,port where order_id = id and hold_id = id and hold_id = 00001
while ( @nextId is not NULL)
begin
print '---working on %1!', @nextId
select @execQuantity = quantity, @buysell = buysell from exec,order where id = @nextId and id = order_id
if (@buysell = 0)
begin
print '---its a buy---'
select @hldQuantity = @hldQuantity + @execQuantity
end
else
if (@buysell = 2)
begin
print '---its a sell---'
select @hldQuantity = @hldQuantity - @execQuantity
end
select @execId = @nextId
select @nextId = min(id) from exec,order,holding where id = order_id and _id = holding_id and port_id= 00001 and exec_id > @execId
end
print "--the hold quantity %1! --", @hldQuantity

No comments: