Solved

How to get results with CTE query rahter than Loop

Posted on 2014-02-23
1
351 Views
Last Modified: 2014-02-28
I have created a stored procedure with loops that gives me the output I need, but it is slow. I have tried to use a CTE query, but do not know how to create the TotalSamples. The CTE creates the same number of rows as the looped query, but does not calculate TotalSamples. TotalSamples should be the distinct samplekey by site, collectionYear, germinationYear, plot, habitat
speciesBySiteTeatmentWithLoop.sql
speciesBySiteTreatment.sql
sampleSeedbank50.csv
createSeedbank.sql
siteTreatmentSpeciesSampleOutput.csv
siteTreatmentSpeciesOutputCTE.csv
0
Comment
Question by:dblankman
1 Comment
 
LVL 45

Accepted Solution

by:
Kdo earned 500 total points
ID: 39880842
Hi Blankman,

A CTE won't necessarily replace a store procedure or the necessity of looping on data.  What the CTE does is allow you to break a complex query into smaller pieces and reuse some of the intermediate results without the database rebuilding those results.

If you can't visualize a query that will do what you want, neither a complex query nor a CTE will do what you want any better than your stored procedure.


Kent
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
sql server insert 12 30
sql select record as one long string 21 24
Unable to Uninstall Visual Studio 2015 7 26
Show Results for Latest DateTime in a View 27 25
Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how the fundamental information of how to create a table.

776 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