简体   繁体   中英

How to return data from null INT value using LIKE clause in stored procedure SQL

I have a stored procedure as follows:

@AgencyID VARCHAR(50),
@TNID INT = NULL,
@ProviderName VARCHAR(100) = NULL,
@County VARCHAR(50) = NULL,
@Region VARCHAR(50) = NULL

SELECT * 
FROM CustomerInfo
WHERE AgencyID = @AgencyID 
  AND (TNID LIKE '%' + ISNULL(CAST(@TNID AS VARCHAR(50)), '') + '%') 
  AND (ProviderName LIKE '%' + ISNULL(@ProviderName, '') + '%') 
  AND (County LIKE '%' + ISNULL(@County, '') + '%') 
  AND (Region LIKE '%' + ISNULL(@Region, '') + '%')

The problem I am facing is whenever the integer TNID value is null my query doesn't return anything even thought some of the parameters have values. It doesn't accept null value to return accurate data although i have ISNULL function.

If I use straight C# code, it works perfectly, but I would like to use the same scenario in my stored procedure to prevent SQL injection in the future

string query = "SELECT * FROM CustomerInfo WHERE AgencyID = '" + agency.Text + "' AND TNID LIKE '%" + tnid.Text + "%' AND ProviderName LIKE '%" + prvName.Text + "%' AND County LIKE '%" + countyList.Text + "%' AND Region LIKE '%" + region.Text + "%'";
SELECT *
FROM CustomerInfo
WHERE AgencyID = @AgencyID
  AND (@TNID IS NOT NULL
       AND TNID LIKE '%' + CONVERT(VARCHAR(50),(ISNULL(@TNID,'')) + '%'
       )

You can add @TNID IS NULL with OR condition. This will make your first condition to true when @TNID is NULL . So other conditions will dictate your query result rather than @TNID messing it up.

Below is quick update to your select statement:

    SELECT * FROM CustomerInfo
    WHERE AgencyID = @AgencyID AND (@TNID IS NULL OR TNID LIKE '%' + ISNULL(CAST(@TNID AS VARCHAR(50)), '') + '%') AND (ProviderName LIKE '%' + ISNULL(@ProviderName, '') + '%') AND (County LIKE '%' + ISNULL(@County, '') + '%') AND (Region LIKE '%' + ISNULL(@Region, '') + '%')

I've tested and the following syntax is working on ms sql 2014 :

declare @toto table (Value varchar(20))
insert @toto select '123'
declare @v int
select * from @toto where value like '%' + isnull(cast(@v as varchar(50)),'') + '%'

I believe the problem come from how you call Sql (which you didn't show us). If you are using an Sql procedure, you must set the SqlCommand.CommandType to Procedure, otherwise you can have strange result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM