Search code examples
c#sql-serverspecial-charactersvarcharsqlcommand

SQL Server query Where string has ':' colon in it returns not found


I am trying to query the table to look for record like this:

string owner = "sometextlikethis";
string pictureName = "pexels-photo.jpg_15-Apr-19 07:59:37"; //problem
PictureLibrary _pictureObj = new PictureLibrary();

var connString = db.connStringCompany;
string cmdText = "SELECT ID FROM PictureLibrary WHERE CONVERT(VARCHAR, PictureOwner) =@PictureOwner AND CONVERT(VARCHAR, PictureName) =@PictureName;";

using (var connection = new SqlConnection(connString))
{
    using (var sqlCmd = new SqlCommand(cmdText, connection))
    {
        SqlParameter param1 = new SqlParameter();
        param1.ParameterName = "@PictureOwner";
        param1.Value = owner;
        sqlCmd.Parameters.Add(param1);

        SqlParameter param2 = new SqlParameter();
        param2.ParameterName = "@PictureName";
        param2.Value = pictureName;
        sqlCmd.Parameters.Add(param2);

        connection.Open();

        SqlDataReader dr = sqlCmd.ExecuteReader();

        while (dr.Read()) //record with matching owner is found but if I add pictureName as additional parameter reader does not find anything
        {
            _pictureObj.Id = Convert.ToInt32(dr["ID"]);
        }

        connection.Close();
    }
}

return _pictureObj; 

As I run query, the ID is null because reader does not find anything. I tried the query without pictureName parameter and it works.

I also checked the table and record where given PictureOwner and PictureName match query exists.

I am guessing I have problem with querying for record where parameter contains ':' colon. I am using filename and current date concatenating to create image name before Inserting it to SQL.

Should I change the naming of the file to avoid colon?

EDIT:

The problem was not with the colon ':' but with the length of the VARCHAR missing in the query.


Solution

  • The issue here should be that you convert the PictureOwner to VARCHAR, which will truncate your string. Try to specify the corresponding length like VARCHAR(255)