Reputation: 1708
Is it possible to use T-SQL programming constructs outside the confines of stored procedures and functions? Specifically, can they be used in ad-hoc sql scripts? If so, is the full range of capabilities available (aside from passing in parameters and returning values that I guess would only be supported in stored procedures and functions)?
I'm from an Oracle PL/SQL background. PL/SQL can be used in stored procedures and functions, but also within anonymous PL/SQL code blocks that can be used in ad-hoc sql scripts and do not get stored in the DB. I'd like to know if T-SQL has similar capabilities.
Upvotes: 2
Views: 120
Reputation: 7314
Yes they can take this example solution to the fizzbuzz problem:
declare @counter int
declare @output varchar(15)
set @counter = 1
while @counter < 101
begin
set @output = ''
if @counter % 3 = 0
set @output = 'Fizz'
if @counter % 5 = 0
set @output = @output + 'Buzz'
if @output =''
set @output = @counter
print @output
set @counter = @counter + 1
end
Of course don't fall into the trap of using procedural code to work with data, SQL works best treating data as a set.
Upvotes: 2