cannot find table 0 in c# asp.net - c#

if (ds.Tables[0].Rows.Count > 0)
{
txtid.Text = ds.Tables[0].Rows[0]["id"].ToString();
txttamil.Text = ds.Tables[0].Rows[0]["Tamil"].ToString();
txtenglish.Text = ds.Tables[0].Rows[0]["English"].ToString();
txtmaths.Text = ds.Tables[0].Rows[0]["Maths"].ToString();
txtscience.Text = ds.Tables[0].Rows[0]["Science"].ToString();
txtsocialscience.Text = ds.Tables[0].Rows[0]["SocialScience"].ToString();
}
}
In the above showed error 'cannot find table 0'.
When i enter invalid id, it need to show "ID does not exist".
May i know, what my mistake in my code?
stored procedure:
ALTER PROCEDURE sp_studentresult
(
#id int,
#output varchar(50) output,
#id_student varchar(50)
)
AS
IF EXISTS (SELECT * FROM student WHERE id=#id_student)
BEGIN
SELECT * from studentresult where id_student=#id
END
ELSE
BEGIN
SET #output='Doesn not EXIST'
End
any help would be highly appreciated.
Thanks,

There is no point on complicating your sp with logic.
Why don't you just check if the query has returned any data?
if (ds.Tables[0].Rows.Count > 0)
{
txtid.Text = ds.Tables[0].Rows[0]["id"].ToString();
txttamil.Text = ds.Tables[0].Rows[0]["Tamil"].ToString();
txtenglish.Text = ds.Tables[0].Rows[0]["English"].ToString();
txtmaths.Text = ds.Tables[0].Rows[0]["Maths"].ToString();
txtscience.Text = ds.Tables[0].Rows[0]["Science"].ToString();
txtsocialscience.Text = ds.Tables[0].Rows[0]["SocialScience"].ToString();
}
else
{
// Whatever you want to do if no row is found
}
And a simpler sp, which will return a empty table if nothing is found
ALTER PROCEDURE sp_studentresult
(
#id int
)
AS
-- I have removed the extra id column as not sure why you use it
SELECT * from studentresult where id_student=#id

Your SP doesn't return any tabular data in case of a non existing id. Try change it to something like
IF NOT EXISTS (SELECT * FROM student WHERE id=#id_student)
BEGIN
SET #output='Does not EXIST'
END
SELECT * from studentresult where id_student=#id

Related

How can I select a field from Microsoft SQL Server to send to c#?

I have a table with SystemId as the primary key. I want to select #systemid and send it to the c# form.
Below is c# code
SqlCommand cmdfindsystemid = new SqlCommand("FindSystemId", con);
cmdfindsystemid.CommandType = CommandType.StoredProcedure;
cmdfindsystemid.Parameters.Add("#systemid", SqlDbType.Int);
cmdfindsystemid.Parameters["#systemid"].Direction = ParameterDirection.Output;
int systemid = Convert.ToInt32(cmdfindsystemid.Parameters["#systemid"].Value);
But I don't know the SQL code. It can be something like:
create proc FindSystemId
#systemid int output
as
select SystemId from tbl systems
set #systemid ?????
You must call the ExecuteNonQuery method from the SqlCommand before reading the parameter. For sample:
SqlCommand cmdfindsystemid = new SqlCommand("FindSystemId", con);
cmdfindsystemid.CommandType = CommandType.StoredProcedure;
cmdfindsystemid.Parameters.Add("#systemid", SqlDbType.Int);
cmdfindsystemid.Parameters["#systemid"].Direction = ParameterDirection.Output;
cmdfindsystemid.ExecuteNonQuery();
int systemid = Convert.ToInt32(cmdfindsystemid.Parameters["#systemid"].Value);
Your SQL Server Statement should look like this. Here #IsSuccess is used as the output parameter in SQL Server.
Note: There may be different ways of assigning the value into the parameter #IsSuccess as I have assigned -1, 1 and 2 as per the logic.
You can try this if your primary column is the identity key also.
SET #IsSuccess = (SELECT SCOPE_IDENTITY())
You can also use the The OUTPUT Clause for INSERT and DELETE Statements.
To call this in C# you can follow this previous answer.
CREATE PROCEDURE [dbo].[AddEditTax] #TaxCode INT
,#TaxName VARCHAR(40)
,#TaxValue NUMERIC(18, 3)
,#IsActive BIT
,#UserCode BIGINT
,#IsSuccess AS INT OUTPUT
AS
BEGIN
DECLARE #tempCode BIGINT
SET #IsSuccess = 0
IF (#TaxCode <= 0) -- ADD
BEGIN
SET #tempCode = (
SELECT ISNULL(MAX(TaxCode), 0) + 1 AS TaxCode
FROM Tax_Mst
)
IF (
NOT EXISTS (
SELECT *
FROM Tax_Mst
WHERE TaxName = #TaxName
)
)
BEGIN
INSERT INTO Tax_Mst (
TaxCode
,TaxValue
,TaxName
,IsActive
,CreatedBy
,CreatedDate
)
VALUES (
#tempCode
,#TaxValue
,#TaxName
,#IsActive
,#UserCode
,CONVERT(VARCHAR, getdate(), 109)
)
SET #IsSuccess = 1
END
ELSE
BEGIN
SET #IsSuccess = - 1
END
END
ELSE IF (#TaxCode > 0) -- Update
BEGIN
IF (
NOT EXISTS (
SELECT *
FROM Tax_Mst
WHERE TaxName = #TaxName
AND TaxCode <> #TaxCode
)
)
BEGIN
UPDATE Tax_Mst
SET TaxName = #TaxName
,TaxValue = #TaxValue
,ModifyBy = #UserCode
WHERE TaxCode = #TaxCode
SET #IsSuccess = 1
END
ELSE
BEGIN
SET #IsSuccess = 2
END
END
END
I use the below method to call the above procedure in C# class.
public static int AddEditTax(Tax objTax)
{
int retVal = 0;
DbCommand objdbCmd;
try
{
String strDBName = BaseClass.GetDatabaseName();
Database ObjDB;
ObjDB = DatabaseFactory.CreateDatabase();
objdbCmd = ObjDB.GetStoredProcCommand("AddEditTax");
if (objTax.TaxCode.HasValue)
ObjDB.AddInParameter(objdbCmd, "TaxCode", DbType.Int32, objTax.TaxCode);
else ObjDB.AddInParameter(objdbCmd, "TaxCode", DbType.Int64, DBNull.Value);
ObjDB.AddInParameter(objdbCmd, "TaxName", DbType.String, objTax.TaxName);
ObjDB.AddInParameter(objdbCmd, "TaxValue", DbType.Decimal, objTax.TaxValue);
ObjDB.AddInParameter(objdbCmd, "IsActive", DbType.Boolean, objTax.Status);
ObjDB.AddInParameter(objdbCmd, "UserCode", DbType.Int64, objTax.CreatedBy.Value);
ObjDB.AddParameter(objdbCmd, "IsSuccess", DbType.Int32, ParameterDirection.Output, "", DataRowVersion.Default, null);
ObjDB.ExecuteNonQuery(objdbCmd);
if (ObjDB.GetParameterValue(objdbCmd, "IsSuccess") != DBNull.Value)
retVal = Convert.ToInt32(ObjDB.GetParameterValue(objdbCmd, "IsSuccess").ToString());
}
catch (Exception objEx)
{
ErrorLogDAL objErrorLogManager = new ErrorLogDAL();
objErrorLogManager.AddErrorLog(objEx);
objErrorLogManager = null;
}
finally
{
objdbCmd = null;
}
return retVal;
}
The value of output parameter in page can be used like this.
int isSuccess = Convert.ToInt32(TaxDAL.AddEditTax(objTax));
if (isSuccess == 1)
{
ScriptManager.RegisterStartupScript(this, typeof(Page), "Alert1", "alert('Record saved sucessfully.');", true);
return;
}
else if (isSuccess == 2)
{
PMessage.InnerHtml = "Record already exists";
PMessage.Attributes.Add("class", "errorMessageText");
PMessage.Visible = true;
return;
}
else
{
PMessage.InnerHtml = "Record not saved sucessfully";
PMessage.Attributes.Add("class", "errorMessageText");
PMessage.Visible = true;
return;
}
You can refere this link for the reference.

Get return value from stored procedure - LINQ

I want to get the return value in stored procedure using LINQ, EF. I have seen solutions with T-SQL but that method does not solve the problem. I need to solve it with LINQ.
Return 0 I want to take 1 and -1 according to the result
Stored procedure:
ALTER PROCEDURE [dbo].[Login]
#inTcNu CHAR(11),
#inPass NVARCHAR(MAX),
#inIP NVARCHAR(40),
#rolNu TINYINT OUTPUT,
#kulNu INT OUTPUT
AS
BEGIN
SELECT #kulNu = kullaniciID, #rolNu = rolID
FROM Kullanici WITH(NOLOCK)
WHERE tcNumarasi = #inTcNu AND parola = #inPass;
IF #rolNu >= 0 AND #kulNu >= 0
BEGIN
INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
VALUES (#inTcNu, #inIP, #inPass, GETDATE(), 1);
RETURN 1;
END
ELSE
BEGIN
INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
VALUES (#inTcNu, #inIP, #inPass, GETDATE(), 0);
RETURN 0;
END
RETURN -1;
END
C#, LINQ, EF
using (var ctx = new ktdbEntities())
{
var IP = networkUtils.GetIP();
var rolNu = new ObjectParameter("rolNu", typeof(int));
var kulNu = new ObjectParameter("kulNu", typeof(int));
var output = ctx.Login(model.tcNumarasi, model.parola, IP, rolNu, kulNu);
object value1 = rolNu.Value;
object value2 = kulNu.Value;
}
You can't return values from Stored Procedure like this. You can pass output parameter to achieve it.
Firstly I modified your sp like this;
ALTER PROCEDURE [dbo].[Login]
#inTcNu CHAR(11),
#inPass NVARCHAR(MAX),
#inIP NVARCHAR(40),
#rolNu TINYINT OUTPUT,
#kulNu INT OUTPUT,
#result INT OUTPUT
AS
BEGIN
SELECT #kulNu = kullaniciID, #rolNu = rolID
FROM Kullanici WITH(NOLOCK)
WHERE tcNumarasi = #inTcNu AND parola = #inPass;
IF #rolNu >= 0 AND #kulNu >= 0
BEGIN
INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
VALUES (#inTcNu, #inIP, #inPass, GETDATE(), 1);
set #result = 1;
END
ELSE
BEGIN
INSERT INTO Oturum (tcNumarasi, oturumIP, parola, oturumZamani, girisBasarili)
VALUES (#inTcNu, #inIP, #inPass, GETDATE(), 0);
set #result = 0;
END
set #result = -1;
END
And then I couldn't see ctx.Login method but I assume that you are executing the stored procedure inside it.
using (var ctx = new ktdbEntities())
{
var IP = networkUtils.GetIP();
var rolNu = new ObjectParameter("rolNu", typeof(int));
var kulNu = new ObjectParameter("kulNu", typeof(int));
var resultParam = new ObjectParameter("result", typeof(int));
var output = ctx.Login(model.tcNumarasi, model.parola, IP, rolNu, kulNu,resultParam);
object value1 = rolNu.Value;
object value2 = kulNu.Value;
object result = resultParam.Value; //Get output value
}

get multiple string outputs from stored procedure using entity framework

The following stored procedure displays three strings and a table row result as output.
Is there any way we can display all the results on a mvc view output panel using entity framework?
I could see the first string result in the code below. But is there anyway to get the other two select string outputs and
the table row result.
private CustomerEntities db = new CustomerEntities();
public ActionResult Index()
{
var results = db.usp_CustomerData("124544", 1500);
var abc = results.ToList();
return View();
}
ALTER PROCEDURE [dbo].[usp_CustomerData]
#CustomerID varchar(6),
#MinsBack int
AS
BEGIN
DECLARE #Count int
SET #Count = (SELECT Count(*)
FROM Customer WITH (NOLOCK)
WHERE CustomerID = #CustomerID AND
DATEDIFF(mi, ReceivedAt, GETUTCDATE()) < #MinsBack)
IF (#Count = 1)
SELECT 'Ok: 1 message in Customer table'
ELSE
SELECT 'ERROR: Expected 1 message in Customer table, but found ' + CONVERT(varchar(3), #Count) + ' messages.'
SET #Count = (SELECT Count(*)
FROM CustomerDetails WITH (NOLOCK)
WHERE CustomerID = #CustomerID AND
DATEDIFF(mi, LastUpdatedAt, GETDATE()) < #MinsBack)
IF (#Count = 1)
SELECT 'Ok: 1 record in CustomerDetails table'
ELSE
SELECT 'ERROR: Expected 1 record in CustomerDetails table, but found ' + CONVERT(varchar(3), #Count) + ' records.'
SET #Count = (SELECT Count(*)
FROM CustomerProduct WITH (NOLOCK)
WHERE CustomerID = #CustomerID AND
DATEDIFF(mi, LastUpdatedAt, GETDATE()) < #MinsBack)
IF (#Count = 1)
SELECT 'Ok: 1 record in CustomerProduct table'
ELSE
SELECT 'ERROR: Expected 1 record in CustomerProduct table, but found ' + CONVERT(varchar(3), #Count) + ' records.'
SELECT *FROM Customer where customerID = #CustomerID
END
As suggestion you could create a temporary table in your SQL script which will be used as temporary store.
CREATE TABLE #Results
(
Message VARCHAR(512)
)
Instead of a direct SELECT in each IF or ELSE you should insert the string into the temp table.
At the end you could reach your goal to get all inserted strings to return them by:
SELECT * FROM #Results
To get customers - like you do at the end - you should trigger a new query to database.
Depending on your case you should consider to querying the database by data context instead of querying the database by store procedures.
You need to do something as suggest in this link but I summarized below
For each results set you will need to do a reader.NextResult();
var someReturnObject = new ResultObject();
using (var context = new LinqPadDbContext(#"Server=localhost\SQLEXPRESS;Database=StackOverflow;Trusted_Connection=True;"))
{
var cmd = context.Database.Connection.CreateCommand();
cmd.CommandText = "[dbo].[GetSomeData]";
try
{
context.Database.Connection.Open();
var reader = cmd.ExecuteReader();
var result1 = ((IObjectContextAdapter)context).ObjectContext.Translate<string>(reader);
someResultObject.Text1 = result1.First();
//for each extra result, start here
reader.NextResult();
var users = ((IObjectContextAdapter)context).ObjectContext.Translate<User>(reader);
someResultObject.Users = users.Select(x => x);
//stop here
}
finally
{
context.Database.Connection.Close();
}
}

Only show values of combobox like "love"?

I created a store procedure to select all values of the table.
But I want in C# application, combobox only show values start like love keyword.
Example:
love love
love king
love soft
Don't show item:
long time
union all
My code:
public void HienThiLoaiBCao()
{
LovetoDAL cal = new LovetoDAL();
string keyword = "BC";
int i = cbxTenBaoCao.FindString(keyword);
if (i == -1)
return;
else
{
var dt = cal.Love_GetByTop("", "", "ID DESC");
cbxTenBaoCao.DataSource = dt;
cbxTenBaoCao.DisplayMember = "lover";
cbxTenBaoCao.ValueMember = "lover";
}
}
public DataTable Love_GetByTop(string Top, string Where, string Order)
{
using (var cmd = new SqlCommand("sq_Love_GetByTop", GetConnection()))
{
cmd.CommandType = CommandType.StoredProcedure;
var da = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#Top", Top));
cmd.Parameters.Add(new SqlParameter("#Where", Where));
cmd.Parameters.Add(new SqlParameter("#Order", Order));
var dt = new DataTable();
da.Fill(dt);
return dt;
}
}
USE [LEO]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sq_Love_GetByTop]
#Top nvarchar(10),
#Where nvarchar(500),
#Order nvarchar(500)
AS
Declare #SQL as nvarchar(500)
Select #SQL = 'SELECT top (' + #Top + ') * FROM [Love]'
if len(#Top) = 0
BEGIN
Select #SQL = 'SELECT * FROM [Love]'
END
if len(#Where) >0
BEGIN
Select #SQL = #SQL + ' Where ' + #Where
END
if len(#Order) >0
BEGIN
Select #SQL = #SQL + ' Order by ' + #Order
END
EXEC (#SQL)
Thanks.
One option is to filter out the records that starts with love from your DataTable. You can either use Select method on DataTable directly OR use RowFilter property on default DataView of the table and then bind the filtered results to your combo box.
Something like this with DataView -
DataView dv = dt.DefaultView;
//Apply your filter on data view, for records starting with `love`
dv.RowFilter = "lover like 'love*'";
//and bind you combo box with the data view
cbxTenBaoCao.DataSource = dv;
Rest of the code would be as is.
More on filtering result sets -
http://www.csharp-examples.net/dataview-rowfilter/
https://msdn.microsoft.com/en-us/library/system.data.datatable.select%28v=vs.110%29.aspx
i did not try this code, it's a long time since i code c#.
//get the values from your stored procedure
List<string> values = task.storedProcedures();
//remove items that doesn't start with "love"
values = values.Where(item => item.someValues.StartsWith("love"))
Hope this helps

Insert, Update error: Subquery returned more than 1 row in C#

I have written a SQL script in stored procedure and query by C#.
But it throws an error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
As I know the problem is that the subquery is returning more than one row to the main query. May I know how to solve it? Thank you.
public void insertData(string TransID, string Item, string FromLocation, string Qty, string Requestor, string RefNum, string Remark, string ReasonID, string ReasonRemark, string CreateDate, string CreateUser, string ToLocation)
{
string constr = ConfigurationManager.ConnectionStrings["CIMProRPT01ConnectionString"].ConnectionString;
using (SqlConnection _cn = new SqlConnection(constr))
{
using (SqlCommand _cmd = new SqlCommand("MMSIssue_InsertOrUpdate", _cn))
{
using (SqlDataAdapter da = new SqlDataAdapter(_cmd))
{
_cn.Open();
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.Parameters.AddWithValue("#INV_TRANS_ID", TransID);
_cmd.Parameters.AddWithValue("#INV_ID", Item);
_cmd.Parameters.AddWithValue("#INV_LOCATION", FromLocation);
_cmd.Parameters.AddWithValue("#INV_QTY", Qty);
_cmd.Parameters.AddWithValue("#INV_TRANS_REQUESTOR", Requestor);
_cmd.Parameters.AddWithValue("#INV_TRANS_REFNO", RefNum);
_cmd.Parameters.AddWithValue("#INV_TRANS_REMARK", Remark);
_cmd.Parameters.AddWithValue("#INV_REASON_ID", ReasonID);
_cmd.Parameters.AddWithValue("#INV_REASON_REMARK", ReasonRemark);
_cmd.Parameters.AddWithValue("#INV_CREATE_DATE", CreateDate);
_cmd.Parameters.AddWithValue("#INV_CREATE_USER", CreateUser);
_cmd.Parameters.AddWithValue("#INV_FROMLOC", ToLocation);
_cmd.Parameters.Add("#RecordFound", SqlDbType.Int, 0);
_cmd.Parameters["#RecordFound"].Direction = ParameterDirection.Output;
_cmd.ExecuteNonQuery();
string DeleteWMMRSQL = "DELETE FROM [CIMProRPT01].[dbo].[OTH_INV_QTY_LOC] WHERE INV_QTY = 0 OR INV_QTY is null OR INV_QTY <= '-1'";
SqlCommand cmd3 = new SqlCommand(DeleteWMMRSQL, _cn);
cmd3.ExecuteNonQuery();
_cn.Close();
float INV_QTY = Convert.ToInt32(_cmd.Parameters["#RecordFound"].Value.ToString());
if (INV_QTY == 2)
{
//QTY is more Than existing QTY !!");
Response.Write("QTY is more Than existing QTY !!");
Response.Redirect("MMS_LocationTrans.aspx");
}
else
{
//QTY not able to key in 0
Response.Write("QTY not able to key in 0!!");
}
}
}
}
}
Stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MMSIssue_InsertOrUpdate]
#INV_TRANS_ID VARCHAR(40),
#INV_ID VARCHAR(40),
#INV_LOCATION VARCHAR(40),
#INV_QTY FLOAT,
#INV_TRANS_REQUESTOR VARCHAR(40),
#INV_TRANS_REFNO VARCHAR(40),
#INV_TRANS_REMARK VARCHAR(255),
#INV_REASON_ID VARCHAR(40),
#INV_REASON_REMARK VARCHAR(255),
#INV_CREATE_DATE DATETIME,
#INV_CREATE_USER VARCHAR (255),
#INV_FROMLOC VARCHAR (40),
#RecordFound INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT * FROM OTH_INV_QTY_LOC
WHERE INV_ID = #INV_ID AND INV_LOCATION = #INV_LOCATION)
BEGIN
UPDATE OTH_INV_QTY_LOC
SET [INV_ID] = #INV_ID,
INV_LOCATION = #INV_LOCATION,
INV_QTY = INV_QTY - #INV_QTY
WHERE INV_ID = #INV_ID
AND INV_LOCATION = #INV_LOCATION
INSERT INTO OTH_INV_TRANSACTION (INV_TRANS_ID, INV_ID, INV_TRANS_LOCATION, INV_TRANS_QTY, INV_TRANS_REQUESTOR, INV_TRANS_REFNO, INV_TRANS_REMARK, INV_REASON_ID, INV_REASON_REMARK, INV_CREATE_DATE, INV_CREATE_USER, INV_FROMLOC)
VALUES (#INV_TRANS_ID, #INV_ID, #INV_LOCATION, #INV_QTY, #INV_TRANS_REQUESTOR, #INV_TRANS_REFNO, #INV_TRANS_REMARK, #INV_REASON_ID, #INV_REASON_REMARK, #INV_CREATE_DATE, #INV_CREATE_USER, #INV_FROMLOC)
DECLARE #InvFindQTY FLOAT
SET #InvFindQTY = (SELECT INV_QTY FROM OTH_INV_QTY_LOC)
IF #InvFindQTY >= #INV_QTY
BEGIN
SELECT #RecordFound = 2
END
ELSE
BEGIN
SELECT #RecordFound = 1
END
END
ELSE
BEGIN
SELECT #RecordFound = 0
END
END
The issue is with this line in the stored procedure:
DECLARE #InvFindQTY FLOAT
SET #InvFindQTY = ( SELECT INV_QTY FROM OTH_INV_QTY_LOC)
If you have more than one record in OTH_INV_QTY_LOC, you will receive this error.
It looks like you should be able to fix the problem by adding
WHERE INV_ID = #INV_ID
to ensure that only a single record is selected, i.e.:
SET #InvFindQTY = ( SELECT INV_QTY FROM OTH_INV_QTY_LOC WHERE INV_ID = #INV_ID)

Categories

Resources