0

Good Day everyone!

I've been searching everywhere on how to get a specified query using if-else statement inside a single stored procedure but still no luck on how to achieve those function.

Here's the T-Sql

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[getHistoryList]
@documentNo varchar(150)=null,
@material varchar(150)=null,
@action varchar(10)=null
as

declare @query nvarchar(max);

if (@action = null)
begin
set @query = 'select top 50 * from s_HistoryList order by documentDate desc'
exec sp_executesql @statement=@query
end 

else if (@action = 'search')
begin
set @query = 'select * from s_HistoryList where documentNo like %'+@documentNo+'% or materialName like %'+@material+'%'
exec sp_executesql @statement=@query
end
go

When exec command is called, it only return Command(s) completed successfully instead the value/table of the selected command. Since the @action is null, it should return the following query and when @ action is supplied with value, it should return the 2nd query.

When if-else statement is removed, it returns the first query but there's no means of accessing the 2nd query.

I saw this method here.

Thank you and I appreaciate any help that this post can get.

1
  • @action = null could never be true. Try IF @action IS NULL. Commented Jan 11, 2021 at 3:42

1 Answer 1

1

You would need to print the variable to the value of the variable @action. Eg:

begin
set @query = 'select * from s_HistoryList where documentNo like %'+@documentNo+'% or materialName like %'+@material+'%'
exec sp_executesql @statement=@query
print 'Below is the value of @action'
print @action
end


A point i would make is that NULL comparison wouldnt work with = sign. 

if (@action = null) to be changed to 
if (@action IS NULL)
Sign up to request clarification or add additional context in comments.

5 Comments

I tried changing the '=' sign in @ action into 'IS'. The output is returns the expected table. Thank you for pointing out. The problem is, the 2nd query. I would like to return the table that the sp_executesql makes, not the value that the @ action have. The output result is still the command completed message.
To do that you would remove the sp_executesql portion and write the query directly (ie not in string limiters)
@JohnMichael SQL injection alert. What if someone passes through @documentNo='''; DROP TABLE; SELECT '''
@Charlieface, I have end-to-end encryption and data sanitation for passing data and accessing this stored procedure since there's a possibility of injection even when using stored procedure.
@JohnMichael That's the wrong way to go about it. You don't sanitize, you parameterize. Even dynamic can be parameterized

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.