Search code examples
sql-like

SQL LIKE: How to add string variable in SQL like statement?


Is it possible to add a string variable in SQL Like statement?

This is what i want:

String client = Request.QueryString["Text"];
String cString = "SELECT UserName FROM dbo.UserData WHERE UserName LIKE '" + client + "'%";

There will an error occur when i put cString in SqlCommand.

I think the problem is '" + client + "'% ,but i cant't figur out.

Can someone help me?


Solution

  • You have SQL statement syntax error.

    // SQL Statement
    SELECT UserName FROM dbo.UserData WHERE UserName LIKE 'foo%'
    
    // Script
    String cString = "SELECT UserName FROM dbo.UserData WHERE UserName LIKE '" + client + "%'";