0

I have string variable in c#

String Condition = " And LoginName like ''%"+txtLoginName.text+"%''";

I pass this condition variable to a stored procedure like this:

SqlCommand cmd = new SqlCommand();
cmd.CommandText = "GetAllUserMasterBySearch";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Condition ", Condition );

And my stored procedure is here:

create PROCEDURE [dbo].[GetAllUserMasterBySearch] (  
    @Condition nvarchar(max)  
    ) 
as
    declare @Query  nvarchar(max) 

    set @Query = 'SELECT
                      [UserMasterId], [LoginName], [UserName],
                      [UserType], [MobileNo], [Email],
                      [IsLogin], [IpAddress]
                  FROM  
                      UserMaster      
                  WHERE 
                      IsActive = 1 ' + @Condition

    print @query   

    EXEC sp_executesql @Query

How to pass "like" condition from C# ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bhavin
  • 240
  • 7
  • 19

1 Answers1

1

You can pass only variable and rewrite your SP as following

alter PROCEDURE [dbo].[GetAllUserMasterBySearch] (  
    @var nvarchar(max)  
) as

declare @Query  nvarchar(max) 
set @Query = 'SELECT
                  [UserMasterId]
                 ,[LoginName]
                 ,[UserName]
                 ,[UserType]
                 ,[MobileNo]
                 ,[Email]
                 ,[IsLogin]
                 ,[IpAddress]
              FROM  
                  UserMaster      
              WHERE 
                  IsActive=1 AND LoginName LIKE %' + @var + '%';

print @query   
EXEC sp_executesql @Query

Update: If you want to play with dynamic SQL then try ''' instead of ''. Honestly I haven't deal with dynamic SQL for a while since it it terrible and not secure approach (as it was already mentioned in comments)

IgorM
  • 1,348
  • 1
  • 12
  • 28
  • @BhavinChhatrola, revised – IgorM Feb 14 '16 at 15:08
  • 1
    @BhavinChhatrola, if you have many columns you shall pass all values as variables and rewrite your SP accordingly with use of WHERE and CASE. This can help: http://stackoverflow.com/questions/206484/sql-switch-case-in-where-clause – IgorM Feb 14 '16 at 15:11