简体   繁体   中英

Stored Procedure doesn't return records when called from C#, but works in SSMS

I have a stored procedure that correctly returns records when I call it from a SSMS query.

Here is the stored procedure:

CREATE PROCEDURE [dbo].[q_CheckRecords]
    @ItemIDS AS VARCHAR(40)
AS
BEGIN
    SET NOCOUNT ON

    SELECT * 
    FROM q_Warehouse80_OOS_ItemsNeedingNotification 
    WHERE item_id  = @ItemIDS
END

Calling this from a SSMS query like this:

exec [q_CheckOOSWarehouse80ItemsNeedingNotification] 'B30-R10000-B001'

It correctly returns a row, however when I use this C# code to call the stored procedure, I never get any rows returned.

SqlCommand cmd = null;
SqlDataReader myReader = null;
System.Data.SqlClient.SqlConnection conn = null;

 conn = new System.Data.SqlClient.SqlConnection("Data Source=" + sSessionServer + ";database=" + sSessionDatabase + "; Integrated Security=SSPI");

  String SQL = "[q_CheckOOSWarehouse80ItemsNeedingNotification]";

  cmd = new SqlCommand();
  cmd.CommandText = SQL;
  cmd.CommandType = System.Data.CommandType.StoredProcedure;
  cmd.Connection = conn;
  cmd.Parameters.Add("@ItemIDS", SqlDbType.VarChar).Value = ItemsToBeChecked;

  conn.Open();
  myReader = cmd.ExecuteReader();

  // check to see if any rows were returned.
  if (myReader.HasRows)
  {
       while (myReader.Read())
       {                                   
            // code to read fields in returned rows here
       }
  }

  conn.Close(); 

It appears to be a problem with how C# defines the datatype being passed to the stored procedure, but I haven't found any information online on how to solve this problem.

If I were to changed the stored procedure so it's "hard coded"

@ItemIDS AS VARCHAR(40)
AS
BEGIN
    SET NOCOUNT ON
    select * from q_Warehouse80_OOS_ItemsNeedingNotification where item_id  =  'B30-R10000-B001'
END

then the C# call to it correctly indicates that a row was "found".

Any help would be greatly appreciated.

When you don't specify the length of a varChar sql treats it as length 1 .

cmd.Parameters.Add("@ItemIDS", SqlDbType.VarChar).Value = ItemsToBeChecked;

Your variable ItemsToBeChecked will be truncated, and I suspect there is nothing matching in your database with just the first character of that value.

Specify the length of the varchar

cmd.Parameters.Add("@ItemIDS", SqlDbType.VarChar, 40).Value = ItemsToBeChecked;

You can verify this is the case by putting a profiler on sql, and executing your c#. You will see the value passed to the @ItemIDS parameter is only 1 character long.

您遇到的问题是因为您没有在C#代码中调用存储过程。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM