C # check if record exists in SQL error

I use this code to check if the value (guid1) exists in the table "guid":

string selectString = "SELECT guid" + "FROM trafficScotland" + "WHERE guid = " + guid1;

SqlCommand myCommand = new SqlCommand(selectString, myConnection);
String strResult = String.Empty;
strResult = (String)myCommand.ExecuteScalar();

 if (strResult.Length == 0)

But on

 strResult = (String)myCommand.ExecuteScalar();

i get sqlException error

Incorrent syntax next to 'guid'

Please show me what's wrong here?

+5
source share
9 answers

selectString = "SELECT guid " + "FROM trafficScotland" + " WHERE guid = '" + guid1 +"'";

Note the space after guid

+2
source
"SELECT guid" + "FROM trafficScotland" + "WHERE guid ="

It:

SELECT guidFROM trafficScotlandWHERE guid =

In any case, it makes no sense to break it into separate lines, but you do not have enough spaces between words :)

string resultGuidAsString = null;

// build command object
string cmdQuery = "SELECT guid FROM trafficScotland WHERE guid=@guid";
SqlCommand myCmd = new SqlCommand(cmdQuery, myConnection);

// safely pass in GUID parameter value
myCmd.Parameters.AddWithValue("@guid", guid1);

// read result, check for nulls in DB
object result = myCmd.ExecuteScalar();
if (result != DBNull.Value && result != null)
{
    resultGuidAsString = result.ToString();
}

^^ Here is an improved version. A few points for criticism if I can:

  • No parameters were used for your request: just building one line. Risk of safety, readability and maintainability.
  • , , , , , DBNull.Value,
  • - string, Guid s. .
+12

- :

var selectString = "SELECT 1 FROM trafficScotland WHERE guid = @guid"
var myCommand = new SqlCommand(selectString, myConnection);
myCommand.Parameters.AddWithValue("@guid", guid1);

var itExists = (Int32)myCommand.ExecuteScalar() > 0;
if (itExists) {
    // do stuff...
}
+6

, . , . ? , ?

SQL Server Profiler. , . , , SQL Server, SQL Server Management Studio .

+2

SQL-. , , (, GUID):

var selectString =  "SELECT guid FROM trafficScotland WHERE guid = @guid";
var myCommand = new SqlCommand(selectString, myConnection);
myCommand.Parameters.AddWithValue("@guid", guid1);
strResult = (String)myCommand.ExecuteScalar();
+2

, , sql.

SELECT guidFROM trafficScotlandWHERE guid

-, . sql-, , sql.

var query = "SELECT guid FROM trafficScotland WHERE guid = @guid";
using(var command = new SqlCommand(query, connection))
{
    command.Parameters.AddWithValue("@guid", guid1);

    var result = command.ExecuteScalar();

    // Compare guid1 to result
}
+2

, ,

SELECT guidFROM trafficScotlandWHERE guid = {guid here}

- , .

+1
source

try the following:

string selectString = "SELECT guid FROM trafficScotland WHERE guid = '" + guid1 + "'";
+1
source

whitespace + enclose a guid with a "", as others have mentioned. You should also store GUIDsas UNIQUEIDENTIFIERs(assuming MSSQL)

0
source

All Articles