SqlCommand.ExecuteScalar returns null but raw SQL does not

邮差的信 提交于 2019-12-11 18:34:54

问题


I have the following code that uses the SqlClient.ExecuteScalar method to return an ID from a table.

using (var conn = new SqlConnection(connectionString))
using (var cmdContrib = new SqlCommand("SELECT ContributorId FROM Contributor WHERE Code='" + folderSystem.ContributorCode + "'", conn))
{
    conn.Open();
    var contribId = cmdContrib.ExecuteScalar();
}

Originally it was working but now contribId is null. I tested the SQL in management studio after extracting from Profiler and it returned the ID as expected.

Next I added an additional command to retrieve an ID from a different table (Product).
productId is not null while contribId continues to be null.

using (var conn = new SqlConnection(connectionString))
using (var cmdContrib = new SqlCommand("SELECT ContributorId FROM Contributor WHERE Code='" + folderSystem.ContributorCode + "'", conn))
using (var cmdTest = new SqlCommand("SELECT productId FROM Product WHERE [filename] = 'bda00001.jpg'", conn))
{
    conn.Open();
    var contribId = cmdContrib.ExecuteScalar();
    var productId = cmdTest.ExecuteScalar();
}

I am sure it is something obvious and I'll kick myself for not noticing it, but for now I'm stumped.


回答1:


Use Profiler to confirm:

A) how many rows are being returned (I suspect 0) B) What database it is in C) what its login/user context is. D) what the actual entire SQL command is.

Extract this command and re-execute it in the same database to confirm that it does return a value. If this suceeds, then change your execution context to that which the Profiler said that the connection was running under and try again. If it fails now (returns 0 rows) then check to see if the source table (Contributor) may actually be a View that is implementing row-level security.



来源:https://stackoverflow.com/questions/967775/sqlcommand-executescalar-returns-null-but-raw-sql-does-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!