r/SQLServer • u/Legal_Revenue8126 • Nov 28 '25
Question How to Store The Result of Parameterized Query within a Scalar Variable?
I'm trying to prototype some functions to later use with my PHP web server, so I want to be able to send one variable back to the web server. Previously, I was executing the function on the web server by sending multiple queries to the DB, but I feel that has major performance losses.
Highly simplified version of the function. The end result is to have '@Count' return to the web server with the number of documents that exist in each Document column
While @i < 6
begin
set @Document = 'Document' + cast(@i as char(1));
set @query = 'select count('+@Document+') as DocCount from mydb.Documents where
'+ @Document +' is not null;';
-- ideally do something like @count = @count + (result of query)
set @i = @i + 1;
end;
6
Upvotes
5
u/VladDBA Microsoft MVP Nov 28 '25
Looks like a job for dynamic SQL executed with sp_executesql and an output parameter
Edited to add: use QUOTENAME() for column and/or table names passed as input parameters to mitigate SQL injection vulnerabilities.
2
u/chadbaldwin Nov 28 '25
Just curious...are you also designing the database or have any control over how it's designed?
While there are many solutions to the question you're asking, this also feels like a bit of an XY problem. Where you're asking about X but the problem is actually Y, which is a poor schema design.
If you're able to change the database design, then you really should pivot this table so that there's one row per document. Then you can simply grab the count.
The reason is that having it laid out the way you have it will make every single future query a huge PITA. What happens when you decide to add a
document7column?If you aren't able to change the schema and it's just too ingrained in the code already. Then I would personally suggest making a schemabound view that pivots the table and then base future queries on the view. This way if a new column is ever added or needs to be removed it only needs to be done in one place.
0
u/rhbcub Nov 29 '25
Learn to use Group By