Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - perform code for each row of an select

Is it possible somehow to execute some code for each row of an select without using a cursor?

In my case: I'm having a temp table to store some data for a complexe script. At the end i want to pint some informations of this table (limited by some conditions) to the output.

Currently I'm using a cursor with a select to limit the rows of the table. In this cursor I'm using

 print '...'

to generate the output.

There must be an easier way to do such things...

edit:

create table #tmpAttributes(AttributeId uniqueidentifier, Value float, ValueString nvarchar(max), ActionId uniqueidentifier)

insert into #tmpAttributes (AttributeId, Value, ValueString, ActionId)
    select ID,..... -- in this select i'm doing some value conversions, if conversion is not possible i'm using -1

insert into ActionAttribute (ActionDefinitionID, Discriminator, ID, ReferredActionID, ValueDate, ValueListID, ValueMoney, ValueString, ValueUserID)
    select @defId, 'ActionAttributeMoneyEntity', NEWID(), ActionId, null, null, Value, null, null from #tmpAttributes

-- afterwards there is this cursor where I'm printint all rows where Value = -1
like image 925
Dominik Kirschenhofer Avatar asked Sep 16 '13 12:09

Dominik Kirschenhofer


People also ask

What is for each row in SQL?

When constructing the body of an SQL procedure, you can use the FOR EACH ROW loop to perform actions on a set of rows that match a certain condition.

How do I select every nth row in SQL?

Here's the SQL query to select every nth row in MySQL. mysql> select * from table_name where table_name.id mod n = 0; In the above query, we basically select every row whose id mod n value evaluates to zero.


1 Answers

I think you need to provide more detail, but you might be looking for something like:

declare @msg varchar(max)='';

select @msg = @msg + 'Output line: ' + ColumnA + ' -- ' + 'ColumnB' + char(13)+char(10)
from #temp
where ...
;

print @msg;
like image 117
Dan Bellandi Avatar answered Oct 02 '22 19:10

Dan Bellandi