Getting error while inserting table in database? - asp.net

i am inserting table in database using table datatype with the following code:
CREATE TYPE BackUpDoctorLocationAreaRoom AS TABLE (
[RoomId] bigint,
[AreaId] bigint,
[LocationId] bigint
);
Alter proc proc_tblBackUpDoctorInsert
(
#Id uniqueidentifier='',
#BackUpDoctorId uniqueidentifier='1323e1f4-7a93-4b45-9a9b-3840c32fd6d8',
#StartDate datetime='11/08/2012',
#EndDate datetime='11/09/2012',
#StartTime datetime='22:22:22',
#EndTime datetime='01:11:11',
#CreatedBy uniqueidentifier='acf7961c-4111-49ad-a66a-ce7f9ce131bd',
#ModifiedBy uniqueidentifier='acf7961c-4111-49ad-a66a-ce7f9ce131bd',
#createdDate datetime='11/6/12 3:09:58 AM',
#ModifiedDate datetime='11/6/12 3:09:58 AM',
#tblBackUpDoctorsForRooms BackUpDoctorLocationAreaRoom READONLY
)
as
set xact_abort on
declare #newId uniqueidentifier;
set #newId = newid();
insert into tblBackUpDoctor (Id,BackUpDoctorId,StartDate,EndDate,StartTime,EndTime,CreatedBy,ModifiedBy,
createdDate,ModifiedDate,IsActive,isdeleted) values
(#newId,
#BackUpDoctorId,
#StartDate,
#EndDate,
#StartTime,
#EndTime,
#CreatedBy,
#ModifiedBy,
#createdDate,
#ModifiedDate,
1,0)
declare #IdFortblBackUpDoctorsForRooms uniqueidentifier;
set #IdFortblBackUpDoctorsForRooms = newid();
delete from tblBackUpDoctorsForRooms where BackUpRecordId=#id and Roomid in (Select roomid from #tblBackUpDoctorsForRooms)
delete from tblbackupdoctor where id=#id
insert into tblBackUpDoctorsForRooms (BackUpRecordId,Roomid,Araeid,locationid)
Select #newId,roomid,areaid,locationid from #tblBackUpDoctorsForRooms
select #newId
This is the sp in which i am using that table.
My class file's code is :
public string InsertBackUpDoctor(ClsBackUpDoctorProp objProp, DataTable dtLocAreaRoom)
{
String ConnectionString = CCMMUtility.GetCacheForWholeApplication();
String backUpRecordId = "";
SqlParameter[] param = new SqlParameter[12];
param[0] = new SqlParameter("#Id", objProp.Id);
param[1] = new SqlParameter("#BackUpDoctorId", objProp.BackUpDoctorId);
param[2] = new SqlParameter("#StartDate", objProp.StartDate);
param[3] = new SqlParameter("#EndDate", objProp.EndDate);
param[4] = new SqlParameter("#StartTime", objProp.StartTime);
param[5] = new SqlParameter("#EndTime", objProp.EndTime);
param[6] = new SqlParameter("#CreatedBy", objProp.CreatedBy);
param[7] = new SqlParameter("#ModifiedBy", objProp.ModifiedBy);
param[8] = new SqlParameter("#createdDate", CCMMUtility.GetCurrentDateTimeByTimeZone("US Mountain Standard Time"));
param[9] = new SqlParameter("#ModifiedDate", CCMMUtility.GetCurrentDateTimeByTimeZone("US Mountain Standard Time"));
param[10] = new SqlParameter("#CurrentDate", objProp.CurrentDate);
param[11] = new SqlParameter("#tblBackUpDoctorsForRooms ", dtLocAreaRoom);
backUpRecordId = SqlHelper.ExecuteScalar(ConnectionString, "proc_tblbackupdoctorInsertBackUpDoctors", param).ToString();
return backUpRecordId;
}
and here is the error which is coming when i tries to insert :
The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Table-valued parameter 12 ("#tblBackUpDoctorsForRooms"), row 0, column 0: Data type 0xF3 (user-defined table type) has a non-zero length database name specified. Database name is not allowed with a table-valued parameter, only schema name and type name are valid.
I dont know why this coming please help me..

I believe you'd have to change the way you pass your custom parameter:
Not just
param[11] = new SqlParameter("#tblBackUpDoctorsForRooms ", dtLocAreaRoom);
but rather something like
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#tblBackUpDoctorsForRooms";
parameter.SqlDbType = System.Data.SqlDbType.Structured;
parameter.TypeName = "BackUpDoctorLocationAreaRoom";
parameter.Value = dtLocAreaRoom;
param[11] = parameter;

try
parameter.SqlDbType = System.Data.SqlDbType.Structured;
parameter.TypeName = "BackUpDoctorLocationAreaRoom";
and in the call add
backUpRecordId = SqlHelper.ExecuteScalar(ConnectionString,CommandType.StoredProcedure
"proc_tblbackupdoctorInsertBackUpDoctors", param).ToString();

Related

Encountered "ORA-01745: invalid host/bind variable name" when using DbDataAdapter.Update() with ODP.NET

I have a table defined in oracle 11g with below statement:
CREATE TABLE "TESTUSER"."TestTableOracleWriter"
("name" VARCHAR2(100 BYTE),
"group" VARCHAR2(100 BYTE),
"number" NUMBER(*,0),
"creation" DATE,
"sliceidentifier" RAW(100),
CONSTRAINT "TESTTABLEORACLEWRITER_PK" PRIMARY KEY ("name"))
And I am using the following code snippet to update the table with content in the dataTable:
private void BatchInsert(DbConnection connection, DbTransaction transaction, DataTable dataTable, string tableName)
{
DbDataAdapter adapter = ProviderFactories.GetFactory("Oracle.DataAccess.Client").CreateDataAdapter();
DbCommand insertCommand = connection.CreateCommand();
DbParameter parameter1 = insertCommand.CreateParameter();
parameter.DbType = DbType.String;
parameter.ParameterName = "#name";
parameter.SourceColumn = "name";
insertCommand.Parameters.Add(parameter);
DbParameter parameter2 = insertCommand.CreateParameter();
parameter2.DbType = DbType.String;
parameter2.ParameterName = "#group";
parameter2.SourceColumn = "group";
insertCommand.Parameters.Add(parameter2);
DbParameter parameter3 = insertCommand.CreateParameter();
parameter3.DbType = DbType.Int32;
parameter3.ParameterName = "#number";
parameter3.SourceColumn = "number";
insertCommand.Parameters.Add(parameter3);
DbParameter parameter4 = insertCommand.CreateParameter();
parameter4.DbType = DbType.DateTime;
parameter4.ParameterName = "#creation";
parameter4.SourceColumn = "creation";
insertCommand.Parameters.Add(parameter4);
insertCommand.CommandType = CommandType.Text;
insertCommand.CommandText = "INSERT INTO \"TestTableOracleWriter\" (\"name\", \"group\", \"number\", \"creation\") VALUES (:name, :group, :number, :creation)";
insertCommand.Transaction = transaction;
insertCommand.UpdatedRowSource = UpdateRowSource.None;
adapter.InsertCommand = insertCommand;
adapter.UpdateBatchSize = 0;
adapter.Update(dataTable);
}
But sometimes the code will fail with "ORA-01745: invalid host/bind variable name", I've searched on the internet and found some materials saying it has something to do with the oracle reserve word. From the link, "name", "group" and "number" is marked as reserve word. I can change my table column names to make the code work.
But the strangest thing is that the code does not fail all the time, it only fails when dataTable cotains only one row, in other scenarios, it works as expected. Anyone has ideas about that?
You can not use key word as parameter name.
Don't use group and number as parameter name

Stored procedure doesn't return output

I have a simple stored procedure which inserts a users record in a table and should give out its userid.
Here is the stored procedure:
Alter proc spRegistration
#UserId nvarchar(10) output,
#Name nvarchar(20),
#EmailAdd nvarchar(20)
as
begin
Declare #Count int;
Declare #ReturnCode int
Select #Count = Count(EmailAdd)
from tblAllUsers
where EmailAdd = #EmailAdd
if #Count > 0
begin
Set #ReturnCode = -1
end
else
begin
Set #ReturnCode = 1
Insert into tblAllUsers(Name, EmailAdd)
values(#Name, #EmailAdd)
end
Select #UserId = UserId
from tblAllUsers
where EmailAdd = #EmailAdd
Select #ReturnCode as ReturnCode
end
I try to get the userid into a textbox like below :
string CS = ConfigurationManager.ConnectionStrings["hh"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spRegistration", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#EmailAdd", txtEmailAddress.Text);
var UserID = cmd.Parameters.AddWithValue("#UserId", SqlDbType.NVarChar);
UserID.Direction = ParameterDirection.Output;
int ReturnCode = (int)cmd.ExecuteScalar();
if (ReturnCode == -1)
{
lblRegMessage.Text = "This email has already been registered with us.";
}
else
{
lblRegMessage.Text = "You were registered successfully.";
txtUserId.Text=(String)UserID.Value;
}
The table as well as the stored procedure is far too complex,I have simplified it for better understanding of problem.UserId is Alphanumeric.Dont worry about that.
Putting a break point shows a null against var UserID
Where am i going wrong?
You need to Use .ToString() on UserID
txtUserId.Text= UserID.Value.ToString();
EDIT:
var UserID = cmd.Parameters.AddWithValue("#UserId", SqlDbType.NVarChar,50);

Failed to convert parameter value from a String to a Boolean Passing value to SP (ASP.net)

while passing value to stored procedure getting error
"Failed to convert parameter value from a String to a Boolean".
not getting point why i am getting this issue while my code is,
C# code is here ,
invProject.targetprojectId =Convert.ToInt32(this.txtOrderNumber.Text);
invProject.projects = this.txtProjectTitle.Text;
invProject.bridge_cost = Convert.ToDouble(this.txtBridgeCost.Text);
invProject.high_cost = Convert.ToDouble(this.txtHighwayCost.Text);
invProject.bridge_comp = this.ddlbridgeComplexity.SelectedValue.ToString();
invProject.hway_comp = this.ddlHighwayComplexity.SelectedValue.ToString();
invProject.project_type = this.ddlProjectType.SelectedValue.ToString();
invProject.proj_Owner = this.ddlProjectOwner.SelectedValue.ToString();
invProject.ind_Exp = Convert.ToInt32(this.chkIndividualExperience.Checked);
Parameters that are passing are as follows,
SqlParameter projectid = cmd.Parameters.Add("#Target_Project_ID", SqlDbType.Int);
projectid.Value = InvPro.targetprojectId;
SqlParameter title = cmd.Parameters.Add("#Projects", SqlDbType.VarChar);
title.Value = InvPro.projects;
SqlParameter bridgecost = cmd.Parameters.Add("#Bridge_Cost", SqlDbType.Money);
bridgecost.Value = InvPro.bridge_cost;
SqlParameter highwaycost = cmd.Parameters.Add("#Hway_Cost", SqlDbType.Money);
highwaycost.Value = InvPro.high_cost;
SqlParameter bComplexity = cmd.Parameters.Add("#Bridge_Comp", SqlDbType.VarChar);
bComplexity.Value = InvPro.bridge_comp;
SqlParameter hComplexity = cmd.Parameters.Add("#Hway_Comp", SqlDbType.VarChar);
hComplexity.Value = InvPro.hway_comp;
SqlParameter cProjectOwner = cmd.Parameters.Add("#ProjectType", SqlDbType.VarChar);
cProjectOwner.Value = InvPro.project_type;
SqlParameter ProjectOwner = cmd.Parameters.Add("#Proj_Owner", SqlDbType.VarChar);
ProjectOwner.Value = InvPro.proj_Owner;
SqlParameter workclass = cmd.Parameters.Add("#Proj_WCB", SqlDbType.VarChar);
workclass.Value = InvPro.proj_WCB;
SqlParameter INdExp = cmd.Parameters.Add("#Ind_Exp", SqlDbType.Bit);
INdExp.Value = InvPro.proj_WCB;
SP define parameters are,
#Target_Project_ID int,
#Projects varchar(50),
#Bridge_Cost money,
#Hway_Cost money,
#Bridge_Comp nvarchar(50),
#Hway_Comp nvarchar(50),
#ProjectType nvarchar(50),
#Proj_Owner nvarchar(50),
#Proj_WCB nvarchar(50),
#Ind_Exp bit,
while column of table are ,
Target_Project_ID int
Projects nvarchar
Bridge_Cost money
Hway_Cost money
Bridge_Comp nvarchar
Hway_Comp nvarchar
Proj_WCB nvarchar
Proj_Owner nvarchar
Ind_Exp bit
i have tried alot but cant remove error hopes to listen from you soon
Thanks
your problem is here :
SqlParameter workclass = cmd.Parameters.Add("#Proj_WCB", SqlDbType.VarChar);
workclass.Value = InvPro.proj_WCB;
SqlParameter INdExp = cmd.Parameters.Add("#Ind_Exp", SqlDbType.Bit);
INdExp.Value = InvPro.proj_WCB;
You are setting the value of both parameters to the same object while they are of different Sqltypes. One is VarChar and the other is bit.
InvPro.proj_WCB can be either a String or a Boolean.
In your code you are treating it as if it is both.
Convert the value of the variable InvPro.proj_WCB to a boolean would be my guess.

When calling stored procedure, .hasRows keeps staying "false"

I have a stored procedure which I am calling which will return data from a table.
But when I try to populate an .aspx with the data it skips my method from doing it because my method is based on whether a reader detects rows.
Here is my method:
private void editExhibit(int expenseID)//new
{
saveExhibitBtn.Text = "Update Exhibit";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("p_CaseFiles_Exhibits_RetrieveExhibitDetails", conn);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("#ExhibitID", expenseID);
cmd.Parameters.Add(new SqlParameter("#ExhibitID", SqlDbType.Int));
cmd.Parameters["#ExhibitID"].Value = expenseID;
bool hasAttachments = false;
string investigatorID = "";
//bool alreadyInvoiced = false;
bool isExpenseOwner = false;
string fileID = "-1";
try
{
conn.Open();
var reader = cmd.ExecuteReader();
if (reader.HasRows)//////////////////////craps out here bcause hasRows is false....
{
reader.Read();
fileID = reader["FileID"].ToString();
ddlCaseFiles.SelectedValue = fileID;
ddlCaseFiles.Enabled = false;
// retrieve exhibit details here
hasAttachments = (bool)reader["HasAttachments"];
investigatorID = reader["InvestigatorID"].ToString();
if (Session["InvestigatorID"].ToString() == investigatorID)
{
isExpenseOwner = true;
}
txtDateReceived.Value = reader["SeizeDate"].ToString();
ddlReceivedBy.SelectedValue = reader["SeizedByInvestigatorID"].ToString();
txtTimeReceived.Value = reader["SeizeTime"].ToString();
txtWhyHowReceived.Value = reader["SeizeAuthority"].ToString();
txtReceivedLocation.Value = reader["SeizeLocation"].ToString();
txtOurItemNum.Value = reader["NewExhibitOutItemNumber"].ToString();////////////
txtTheirItemNum.Value = reader["ClientItemNum"].ToString();
txtBagNum.Value = reader["BagNumber"].ToString();
txtBoxNum.Value = reader["BoxNumber"].ToString();
txtComment.Value = reader["ExhibitDecriptionPlainText"].ToString();
}
}
catch (SqlException ex)
{
ErrorLogger.Log(ex.Number, "NewExhibit.aspx - editExhibit - Retrieve Details", ex.Message);
}
Here is my stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[p_CaseFiles_Exhibits_RetrieveExhibitDetails]
#FilterField nvarchar(max)=null
, #FilterQuery nvarchar(max)=null
, #SortName nvarchar(max)='SeizeDate, SeizeTime '
, #SortOrder nvarchar(max)='desc'
, #ExhibitID int
as
SET CONCAT_NULL_YIELDS_NULL OFF
declare #Command nvarchar(max)
Select #Command = 'select E.ExhibitID,convert(nvarchar,SeizeDate,111) as ''SeizeDate'',SeizeTime,ExhDesc,E.InvestigatorID as ''EnteredBy''
,E.SeizedByInvestigatoID as ''SeizedBy'',SBI.ActiveInvestigator, SBI.FName+'' '' + SBI.LName as ''SeizedByName'', E.FileID,[FileName]
,Investigators.FName,Investigators.LName,SzAuthority,Location,ItemID,SubItemID1,SubItemID2,SubItemID3,PageSerial,ClientItemNum,Privileged
,Private,E.HasAttachments,ItemEntryGradeID,BagNumber,BoxNumber,PL.PropertyId,P.PropertyTypeID,P.PropertyMakeID,P.PropertyModelID,SerialNumber,ColorID
,cast(ItemID as varchar)+''-''+cast(SubItemID1 as varchar)+''-''+cast(SubItemID2 as varchar)+''-''+cast(SubItemID3 as varchar) as ''ItemNumber'',StoredLocally
from CaseFileExhibits E
join Investigators on E.InvestigatorID = Investigators.InvestigatorID
join Investigators SBI on SBI.InvestigatorID=E.SeizedByInvestigatoID
join CaseFiles on E.FileID = CaseFiles.FileID
left join CaseFileExhibitPropertyLink PL on E.ExhibitID=PL.ExhibitID
left join Element09a_Properties P on P.PropertyID=PL.PropertyId
left join ElementPropertyTypes PT on PT.PropertyTypeID=P.PropertyTypeID
left join ElementPropertyMakes PM on PM.PropertyMakeID=P.PropertyMakeID
left join ElementPropertyModels PMD on PMD.PropertyModelID=P.PropertyModelID
where E.ExhibitID='+convert(nvarchar,#ExhibitID);
if(#FilterQuery is not null)
begin
select #Command+=' and '+#FilterField+ ' like '''+#FilterQuery+''' ';
end
select #Command+=' order by '+#SortName+' '+#SortOrder
So according to the stored procedure I only need to pass in the exhibitID, which I did.
Your Stored procedure looks incomplete. You probably need to add
exec sp_executesql #command;
At the end to get it to return your rows.
info about sp_executesql can be found at http://msdn.microsoft.com/en-us/library/ms188001.aspx

Correct syntax in stored procedure and method using MsSqlProvider.ExecProcedure?

I have problem with ASP.net and stored procedure
My procedure in SQL Server:
ALTER PROCEDURE [dbo].[top1000]
#Published datetime output,
#Title nvarchar(100) output,
#Url nvarchar(1000) output,
#Count INT output
AS
SET #Published = (SELECT TOP 1000 dbo.vst_download_files.dfl_date_public FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC )
SET #Title = (SELECT TOP 1000 dbo.vst_download_files.dfl_name FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
SET #Url = (SELECT TOP 1000 dbo.vst_download_files.dfl_source_url FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
SET #Count = (SELECT TOP 1000 dbo.vst_download_files.dfl_download_count FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
And my procedure in website project
public static void Top1000()
{
List<DownloadFile> List = new List<DownloadFile>();
SqlDataReader dbReader;
SqlParameter published = new SqlParameter("#Published", SqlDbType.DateTime2);
published.Direction = ParameterDirection.Output;
SqlParameter title = new SqlParameter("#Title", SqlDbType.NVarChar);
title.Direction = ParameterDirection.Output;
SqlParameter url = new SqlParameter("#Url", SqlDbType.NVarChar);
url.Direction = ParameterDirection.Output;
SqlParameter count = new SqlParameter("#Count", SqlDbType.Int);
count.Direction = ParameterDirection.Output;
SqlParameter[] parm = {published, title, count};
dbReader = MsSqlProvider.ExecProcedure("top1000", parm);
try
{
while (dbReader.Read())
{
DownloadFile df = new DownloadFile();
//df.AddDate = dbReader["dfl_date_public"];
df.Name = dbReader["dlf_name"].ToString();
df.SourceUrl = dbReader["dlf_source_url"].ToString();
df.DownloadCount = Convert.ToInt32(dbReader["dlf_download_count"]);
List.Add(df);
}
XmlDocument top1000Xml = new XmlDocument();
XmlNode XMLNode = top1000Xml.CreateElement("products");
foreach (DownloadFile df in List)
{
XmlNode productNode = top1000Xml.CreateElement("product");
XmlNode publishedNode = top1000Xml.CreateElement("published");
publishedNode.InnerText = "data dodania";
XMLNode.AppendChild(publishedNode);
XmlNode titleNode = top1000Xml.CreateElement("title");
titleNode.InnerText = df.Name;
XMLNode.AppendChild(titleNode);
}
top1000Xml.AppendChild(XMLNode);
top1000Xml.Save("\\pages\\test.xml");
}
catch
{
}
finally
{
dbReader.Close();
}
}
And if I made to MsSqlProvider.ExecProcedure("top1000", parm); I got
String[1]: property Size has invalid size of 0.
Where I should look for solution? Procedure or method?
You need to specify the length property for url and Title
SqlParameter title = new SqlParameter("#Title", SqlDbType.NVarChar);
title.Size=1000
SqlParameter url = new SqlParameter("#Url", SqlDbType.NVarChar);
url.Size=1000
Instead of using an output parameter you can change your query like the one below
ALTER PRocedure [dbo].[top1000]
As
Begin
Select top 1000 dfl_date_public ,dfl_name,dfl_source_url,
dfl_download_count from dbo.vst_download_files
order by dbo.vst_download_files.dfl_download_count DESC
Then use execute reader
SqlCommand command =
new SqlCommand("top1000", connection);
command.CommandType=CommandType.StoredProcedure
SqlDataReader reader = command.ExecuteReader();
// Iterate through reader as u did and add it to the collection
use xelement to frame the XML
foreach (DownloadFile df in List)
{
XElement products=
new XElement("Products",
new XElement("product",
new XElement("published", "data dodania"),
new XElement("title", df.Name)
);
}

Resources