I want to create a stored procedure in SQL Server 2017 and let it be called somewhere else (i.e., Python). It accepts three parameters, stkname
- stock name, stktype
- stock type, colname
- output columns (only these columns are returned). @colname
is a varchar
storing all required column names separated by ,
.
- If
@colname
is not specified, return all columns (*
) - If
stkname
orstktype
is not specified, do not filter by it
This is my code so far:
create procedure demo
(@stkname varchar(max),
@colname varchar(max),
@stktype varchar(max))
as
begin
----These lines are pseudo code -----
select
(if @colname is not null, @colname, else *)
from
Datatable
(if @stkname is not null, where stkname = @stkname)
(if @stktype is not null, where stktype = @stktype)
---- pseudo code end here-----
end
The desired result is that
exec demo @colname= 'ticker,price', @stktype = 'A'
returns two columns - ticker and price, for all records with stktype = 'A'
I could imagine 'dynamic SQL' would be possible, but not that 'elegant' and I need to write 2*2*2 = 8 cases.
How can I actually implement it in a better way?
PS: This problem is not a duplicate, since not only I need to pass column names, but also 'generate a query by other parameters'