user1199739
user1199739

Reputation: 2823

WHERE clause in a SQL statement in C#

I am trying to define two conditions for a WHERE clause:

WHERE Date = @date (already implemented)
and
WHERE Type = @currenttype

Code as follows:

string sql = string.Format("SELECT Result FROM {0} WHERE Date = @date", hostnameclear);

Would I use two WHERE clauses, or can I specify two conditions?

Upvotes: 1

Views: 9743

Answers (7)

Pranay Rana
Pranay Rana

Reputation: 176886

try

SELECT Result FROM {0} WHERE Date = @date and Type = @currenttype 

just remove second "Where" will do you task

Upvotes: 2

chunk
chunk

Reputation: 19

The best practice when you program in C#, Java, Perl whatever is to ensure that your sql syntax is correct by using commandline tools like sqlplus or any other sql prompt. This helps a lot for this kind of errors.

Upvotes: 0

Oded
Oded

Reputation: 498914

You don't need two WHERE clauses.

This is correct:

WHERE Date = @date
AND Type = @currenttype

I would urge you to use parameterized queries instead of string.Format, as you are opening your code up to SQL Injection.

This is still possible to do with dynamic SQL (seeing as you are specifying the table name, dynamic SQL is probably required).

Upvotes: 4

iefpw
iefpw

Reputation: 7042

where data = @data AND somecolumn = issomething.

one where with "and" statements.

Upvotes: 0

Alex Mendez
Alex Mendez

Reputation: 5150

I would have one where statement.

string sql = string.Format("SELECT Result FROM {0} WHERE Date = @date AND Type = @currenttype", hostnameclear);

Upvotes: 0

FishBasketGordo
FishBasketGordo

Reputation: 23122

You only need one WHERE:

SELECT Result FROM {0} WHERE Date = @date AND Type = @type

Upvotes: 0

Grant Thomas
Grant Thomas

Reputation: 45083

You don't need the second WHERE clause: the following statements fall within that context, you would join them with AND, and the next clause would start with the next command, say ORDER BY.

Upvotes: 1

Related Questions