PDA

View Full Version : سوال: اجرا نشدن stored procedure



ziduat
یک شنبه 23 تیر 1392, 12:05 عصر
سلام به همه
من یک stored procedure نوشتم که بر اساس یه شرط یا باید 1 یا -1 رو برگردونه. به صورت زیر:
ALTER PROCEDURE [dbo].[check]

AS
BEGIN

if exists(select personnelcode
from table1
where table1.personnelcode not in (select personnelcode
from table2))
return (-1)
else
return 1

END

توی ویژوال هم به این صورت نوشتم:

public static int operatequery(string storedprocedurename)
{
connection = new SqlConnection(connectionstring);
try
{
SqlCommand command = new SqlCommand(storedprocedurename, connection);
command.CommandTimeout = int.MaxValue;
command.CommandType = CommandType.StoredProcedure;
connection.Open();

object returnvalue = command.ExecuteScalar();
connection.Close();
return int.Parse("0" + returnvalue);
}
catch (Exception ex)
{
connection.Close();
return -1;
}
}


و بعد این تابع رو توی رویداد یک button فراخوانی کردم ولی مشکلی که داره اینه که return value توی تابع null هست و مقدار نمی گیره
ممنون میشم راهنمایی کنید.

veniz2008
یک شنبه 23 تیر 1392, 13:20 عصر
سلام.
sp خودتون رو بصورت زیر بنویسید و از پارامتر خروجی برای ارسال 1 یا 1- استفاده کنید :

ALTER PROCEDURE [dbo].[check]
@result int output
AS

if exists(select personnelcode
from table1
where table1.personnelcode not in (select personnelcode
from table2))
set @result = -1
else
set @result = 1
در سمت سی شارپ هم مقدار رو بصورت زیر دریافت کنید :

--------------------
connection = new SqlConnection(connectionstring);
SqlCommand command = new SqlCommand("check",connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@result", SqlDbType.Int);
command.Parameters["@result"].Direction = ParameterDirection.Output;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
int res = Convert.ToInt32(command.Parameters["@result"].Value);
if (res == -1)
MessageBox.Show("کد پرسنلی در جدول اول هست که در جدول دوم نیست");
else if (res == 0)
MessageBox.Show("تمامی کدهای پرسنلی موجود در جدول اول، در جدول دوم نیز وجود دارند");
موفق باشید.

ziduat
دوشنبه 24 تیر 1392, 12:10 عصر
ممنون از راهنماییتون :چشمک: