我有两张桌子:
questionbank table
qustion answer1 answer2 answer3 answer4 correct_ans sub_name
result table
username name correctanswer totalquestions percentage result sub_name
我想在这两者之间执行内部联接,以便从问题库表中读取结果并在结果表中存储我如何在sql server 2008.please help中执行此操作。
我也有c#的代码:
SqlCommand cmd = new SqlCommand(
@"SELECT COUNT(result.username) AS correct_ans
FROM result
INNER JOIN questionbank ON result.Q_id = questionbank.Q_id
AND result.User_Ans = questionbank.Correct_Ans
AND result.username = " + username + " ");
SqlCommand cmd1 = new SqlCommand(
@"SELECT COUNT(Q_id) AS totalquestions FROM questionbank";);
答案 0 :(得分:2)
你所拥有的基本上是好的(尽管r.username
应该是where
,而不是join
条款);你真的非常应该参数化,但是:
using(var cmd = new SqlCommand(@"
SELECT COUNT(r.username) AS correct_ans
FROM result r
INNER JOIN questionbank q ON r.Q_id = q.Q_id AND r.User_Ans = q.Correct_Ans
WHERE r.username = @username"))
{
cmd.Parameters.AddWithValue("username", username))
// use it; since it returns a single COUNT, we can probably use:
int correct = (int)cmd.ExecuteScalar();
//...etc
}
除此之外:它应该没问题。如果您没有看到匹配项,那么请在SSMS中尝试查询,确保在其前面加上以下内容:
declare @username nvarchar(200) = 'Fred';
(或其他)。在对像username
这样的值进行过滤时,我的直接想法是"区分大小写" - SQL Server可以区分大小写或不区分大小写:您将其配置为区分大小写,然后'Fred'
与'fred'
或'FRED'
或'FrEd'
不匹配。< / p>
答案 1 :(得分:1)
这会在你运行时出错,因为在result.username之后你必须这样写 result.username =&#39;&#34; +用户名+&#34;&#39;。不要忘记使用&#39;用户名前后的char。最好使用参数化查询。 我认为你已经做了内连接还有另一个问题吗?