Solved

SQL select statement that returns a row for every value in a while loop

Posted on 2013-01-31
9
453 Views
Last Modified: 2013-04-22
Alright I've got two tables in two separate DB's... which I am joining to write to a table in a third DB.. Every 10 miuntes I'm going to delete the values in th tird table and write from the other 2 again... becasue of a later use of the third tabel I need to show records whether or not the select statement from the joined tables returns a value...

How can I do this....

Code below....

delete CurrentlyRunning.dbo.ExpectTput -- output table which needs to have 20 records each time

declare @rpline int --counter for while loop

set @rpline = -1
while @rpline < 20
Begin
set @rpline = @rpline +1

insert into CurrentlyRunning.dbo.ExpectTput

select  
@rpline,
spwo.item,
unit_weight,
pcs_per_mch_hr,
(pcs_per_mch_hr * unit_weight)

from [spdaccess]...[work order] spwo  
inner join item on spwo.item = item.item
inner join jrt_sch on item.job = jrt_sch.job
and jrt_sch.suffix = 1
where [order status] = 5
and [End Date] is null
and @rpline = spwo.line
order by line
end

Thanks

Z
0
Comment
Question by:ztangent
  • 5
  • 4
9 Comments
 
LVL 12

Expert Comment

by:mwochnick
ID: 38841622
any reason you can't create a view that joins the two tables and looks like the third table and query appropriately against the view instead of repeatedly copying the data into the third table?
0
 

Author Comment

by:ztangent
ID: 38841668
how would I do that... remember the output need to come back showing all 20 lines even if the line is not found in the spwo table....
0
 
LVL 12

Expert Comment

by:mwochnick
ID: 38844239
ok you have a couple of issues - your insert statement assumes that there is a row coming back from the select statement for 20 rows - so you need to some logic to handle the scenario where there isn't a row for alll 20  
second you don't any logic to insert a "blank" row if you select doesn't return a value

One way to do this would be to use a cursor like in this example to insert the valid rows
DECLARE Employee_Cursor CURSOR FOR
SELECT EmployeeID, Title 
FROM AdventureWorks2012.HumanResources.Employee
WHERE JobTitle = 'Marketing Specialist';
OPEN Employee_Cursor;
FETCH NEXT FROM Employee_Cursor;
WHILE @@FETCH_STATUS = 0
   BEGIN
      FETCH NEXT FROM Employee_Cursor;
   END;
CLOSE Employee_Cursor;
DEALLOCATE Employee_Cursor;
GO

Open in new window

from this page http://msdn.microsoft.com/en-us/library/ms178642.aspx
and then do a count of rows into a variable
select @myInt = COUNT(*) from myTable
set @myInt = (select COUNT(*) from myTable)

Open in new window

and use another while loop starting at count to insert the remaining blank rows similar to your current while loop
0
Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

 

Author Comment

by:ztangent
ID: 38844361
Only problem is that the counter is more than just a counter.. it actuall represents a production line in my mfg facility.. There fore the "blank" line is not really "blank" it needs to tell me what line number it didn't find and hopefully be able top write null or "0" for the tput value...

I was thinking over night... would this entire process be easier with an "upset".... instead of a delete and insert... in the destination table write 20 records... line 1 -20... all other fields null or 0... then upsert (merge?) each time I run the sp... only problem is if a line shuts down it will continue to show the last tput... when what I really needit to show at that point is 0...

Any thoughts on how to make it work this direction or am I making it harder on myself...
0
 
LVL 12

Expert Comment

by:mwochnick
ID: 38844486
With the caveat of not understanding your problem fully...I'd make the smarts of this thing in the ui that displays the results and not in the database.

It doesn't seem that you need to keep the history of this stuff in the third table so why store it?  If you don't have 1000's of clients you shouldn't have database performance issues if you only allow the clients to refresh every 10 minutes


but if you need to store it in the table then you could add some if else logic around the select to check if it has the values you want before inserting appropriately so
so inside your while loop
select fields into some variables
if the fields have the correct values
  do your insert from the select
else
  do your custom insert for with the 0's and nulls

IF - ELSE
http://msdn.microsoft.com/en-us/library/ms182717.aspx
0
 

Author Comment

by:ztangent
ID: 38844957
whats the if logic to tell me the select did not return any data...??
0
 

Author Comment

by:ztangent
ID: 38844959
I also tried thsi which failed due to syntax...

declare @rpline int
declare @rpitem nvarchar(50)
declare @rpweight float
declare @rppcsphr float
declare @rptput float


set @rpline = -1
while @rpline < 20
Begin
set @rpline = @rpline +1
set @rpitem = null
set @rpweight = 0
set @rppcsphr = 0
Set @rptput = 0

select  
@rpline,
spwo.item into @rpitem,
unit_weight into @rpweight,
pcs_per_mch_hr into @rppcsphr ,
(pcs_per_mch_hr * unit_weight) into @Rptput

from [spdaccess]...[work order] spwo  
inner join item on spwo.item = item.item
inner join jrt_sch on item.job = jrt_sch.job
and jrt_sch.suffix = 1
where [order status] = 5
and [End Date] is null
and @rpline = spwo.line
order by line

insert into CurrentlyRunning.dbo.ExpectTput

@rpline,
@rpitem,
@rpweight,
@rppcsphr,
@rptput


end
0
 
LVL 12

Accepted Solution

by:
mwochnick earned 500 total points
ID: 38845082
if the select you run returns 0 rows when empty then you could use the select count I had in the earlier post for your if logic  instead of what i had suggested later

pseudo code
count = select count().....
if count = 0 then
 insert blank
else
 insert your select
0
 

Author Closing Comment

by:ztangent
ID: 39101062
ended up using my own solution but thanks for all of the feedback and help
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question