Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 List merchant based on search input parameter

Author  Topic 

dhinasql
Posting Yak Master

195 Posts

Posted - 2014-01-01 : 03:01:19
Friends,
I am new for SQL SP
I have three table,

Table 1 - Merchant

MerchantID MerchantName Zip
1 Merchant1 1001
2 Merchant2 1002
3 Merchant3 1003
4 Merchant4 1004

Table 2 - Region

RegionID RegionName
1 Region1
2 Region2
3 Region3

Table 3 - Offer

OfferID RegionID MerchantID
1 1 3
2 1 2
3 1 1
4 2 2
5 2 4

I have two input parameter for this SP, @MerchantName = NULL and @RegionName = NULL

Expected Result Table

If input parameter @MerchantName = NULL and @RegionName = NULL

MerchantID MerchantName Zip
1 Merchant1 1001
2 Merchant2 1002
3 Merchant3 1003
4 Merchant4 1004

If we Search by RegionName="Region1" Ex: @MerchantName = NULL and @RegionName = 'Region1'

MerchantID MerchantName Zip
1 Merchant1 1001
2 Merchant2 1002
3 Merchant3 1003

If we Search by RegionName="Region2" Ex: @MerchantName = NULL and @RegionName = 'Region2'

MerchantID MerchantName Zip
2 Merchant2 1002
4 Merchant4 1004

If we search by MerchantName='Merchant1' Ex: @MerchantName = 'Merchant1' and @RegionName = ''

MerchantID MerchantName Zip
1 Merchant1 1001


Please help me to get the expected result for the above scenario

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-01-01 : 10:58:37
you need to use a logic like below

CREATE PROC GetMerchantDetails
@MerchantName varchar(100)= NULL,
@RegionName varchar(100) = NULL
AS
SELECT *
FROM Merchant m
WHERE EXISTS(SELECT 1
FROM Offer o
INNER JOIN Region r
ON r.RegionID = o.RegionID
WHERE o.MerchantID = m.MerchantID
AND (r.RegionName = @RegionName
OR @RegionName IS NULL)
)
AND (MerchantName = @MerchantName
OR @MerchantName IS NULL)
GO


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

dhinasql
Posting Yak Master

195 Posts

Posted - 2014-01-02 : 12:04:03
Thank you so much Visakh, Its working great...
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-01-02 : 12:24:08
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -