SQL Server Stored Procedure - Use Row Count in Select query - sql-server-2005

My stored procedure (SQL Server 2005) returns a dataset where one field depends, among other things, on the number of rows returned by the query. I can make a simplified first query that allows me to get ##ROWCOUNT but, in that case, the procedure returns the two sets, which is not what I want.
I tried putting the first query in a WITH statement but haven't found the syntax to extract the row count and put it in a variable that I could use in the second query. An alternative would be to get ##ROWCOUNT from the first query and tell the procedure to return only the result of the second query.
There are probably better ways to do that but my expertise in SQL is quite limited...
Thanks for any help!

Is this what you're looking for? If not, could you please describe your problem in more details (perhaps, with code snippets)
alter procedure ComplicatedStoredProcedure as
begin
declare #lastQueryRowCount int
-- Storing the number of rows returned by the first query into a variable.
select #lastQueryRowCount =
-- First resultset (not seen by caller).
(select count(*) from A where ID > 100)
-- Second resultset. This will be the actual result returned from the SP.
select * from B where SomeDependentField > #lastQueryRowCount
end

Related

Oracle Multi Column Subquery with a procedure call

I have an interesting problem from work. I have an Oracle procedure written by someone else that returns a dataset (multi-column, multi-row) for a single input person ID. I need to use this procedure to get the dataset for all person IDs.
The procedure can be queried by casting the output as a table:
"select * from table (package.proc(in_ID))"
The only way I know how to query this is to make multiple proc calls like this:
select ID,
(select col1 from table(package.proc(persons.ID)) as col1,
(select col2 from table(package.proc(persons.ID)) as col2, --(etc...)
from persons
However, for the number of rows and columns I need to get from this thing, this is terribly inefficient and causes server timeouts. Also, the subselects can only get one row from the proc so I also have missing rows (or if it returns more than one row it errors on the subselect).
Is there a way to do this that doesn't involve rewriting the procedure to return the data for all person IDs?
Starting from Oracle 12c you could use CROSS/OUTER APPLY:
SELECT *
FROM persons p
OUTER APPLY(TABLE(package.proc(p.ID))) s;

How to re-use a SQL query in a PL/SQL procedure?

I am writing a PL/SQL procedure. In the body of this procedure, how can I use twice the same query without re-writing it ?
To simplify, let's say that I have this SQL query :
SELECT *
FROM mytable
WHERE age > 18
Is there a way to "store it", so I could do for example :
SELECT COUNT(*) INTO var1
FROM myQuery
I know the WITH ... AS keywords, but as I know it can be only used in the current statement, and I want to be able to call it from different statements.
Thanks !
There are various possibilities. Here are the ones I think of immediately, there are probably others:
Declare an explicit CURSOR using your query, and use that cursor multiple times in the body of your procedure.
Store the query in a string variable, and use EXECUTE IMMEDIATE to run it multiple times
Execute the query once, storing the results in a local collection (nested table, most likely), and process those stored results multiple times
Create a function that executes the query and returns its results as a nested-table type. Then SELECT FROM TABLE( my_function ) multiple times

How to use IF condition for column selection in sql server 2008 R2

In my project I want data from same table in 2 different manner.
1) Only 5 fields
2) Only 10 fields
And I am getting the data through Stored Procedure for each one. But I want that if possible I should make one procedure.
So, can I put if condition for selecting column?
For example, if I pass parameter as "Less", it will get data of only 5 columns and if I pass parameter as "More", it will get data of 10 columns. I can have two SELECT statement in procedure based on condition(that I have already done) but I want to make it One SELECT statement. Is it possible?
No, is it not possible to have a single SELECT statement.
But then, you can do this:
if #ColumnList = 'less'
begin
call storedProc_returning5Columns
end
else
begin
call storedProc_returning10Columns
end
[Another option is to use Dynamic TSQL]
This isn't possible.
Your current solution of having an IF statement in the stored procedure is the best approach.

SQL stored procedure combine result

I have written two SQL Server stored procedures
For example:
create PROCEDURE query1
AS
SQL code here...
create PROCEDURE query2
AS
SQL code here...
Now I can call them individually using the following command, and the returned value is the following.
exec query1
Study availability
ACR 99.97%
Now I want to combine these stored procedures and get the results in one shot, like :
exec query1
exec query2
and it give result something like following but somehow its now working its giving me syntax error. How do I combine two stored procedures and get results in one report?
This is T-SQL query
Study availability
ACR 99.97%
FOS 87.88%
You can't call them the way you describe (ie exec query1 exec query2). Here is one alternative assuming each proc returns a single value:
declare #result as table (
ACR float,
FOS float
)
INSERT INTO #result(ACR)
exec query1
INSERT INTO #result(FOS)
exec query2
SELECT ACR,FOS from #result
Since they both return the same column headings/data types I recommend combining the 2 separate queries into a single query and use UNION ALL.
EX:
SELECT 'ACR' AS Study,
SomeField AS Availability
FROM SomeTable1
UNION ALL
SELECT 'FOS' AS Study,
SomeField AS Availability
FROM SomeTable2;
It's hard to give more specific advice without seeing your actual Stored Procedures, but this is definitely much clearer than having 2 separate procedures. Hope this helps.
You can try that:
exec query1; exec query2
But be aware that the result is not combined, you just get the result of both SPs as separate result sets.
It depends on your code, you can insert the results of each SP into a table, and then UNION them together to get the single result set you are looking for - but this often can be slower if it's a lot of rows since you are making copies of the results instead of just streaming them out to the client. And it breaks the ability of the optimizer to combine things across the boundary, since it has to write them to the temporary tables.
If the procs aren't complex, I would consider making them into views or inline table-valued functions. These can be easily combined by other routines like views, functions or procedures and make things a bit more modular.

How to write a update SQL using a select SQL

I want to write a update SQL statement, but one conidtion of this statement is the result from a select SQL statement, and I also want to return the result of the select SQL statement.
Like this: update ... set ... where id = (select id from ...)
I want to return the value of id back.
Does anybody know how should I do this?
Thanks in advance!
I don't believe that's possible in one statement. Update then query (select) the new value, or query the value first, and then submit an update.
Alternative would be a stored procedure on the database, which executes the multiple queries and returns the result for you.
This is not possible in all Java database frameworks that I know. Probably you need to separate your query and update in Java.
I don't see any problem in using a subselect in a WHERE clause of an update statement.
For the second request, getting back the value of id, I know this is possible in DB2, and maybe others implement that syntax too:
SELECT id FROM FINAL TABLE (
update ... set ... where id = (select id from ...)
)
This works also for INSERT and DELETE statements. (See the documentation.)
Update statements won't return the updated datasets. The select in that case would be a subselect that isn't directly accessible.
You'd thus have to use at least two queries:
select the ids you want
call the update query passing the previously selected ids as a parameter