The RefNo column in SQL Server table is of datatype bigint, and can accept Nulls.
I am saving multiple records via xml using c#. The code works good, but for a few records, the RefNo has to be null, and it is saving as 0 even when I comment the 'else' part in stringbuilder.
SQL:
ALTER PROCEDURE SaveActivity
#XMLData xml
AS
BEGIN
IF #XMLData IS NOT NULL
BEGIN
CREATE TABLE #Temp(
ActivityId uniqueidentifier,
RefNo int,
Notes nvarchar(500)
);
INSERT INTO tblActivityDetails(ActivityId,RefNo,Notes)
SELECT
detail.query('ActivityId').value('.','uniqueidentifier') as ActivityId,
detail.query('RefNo').value('.','int') as RefNo,
detail.query('Notes').value('.','nvarchar(500)') as Notes
FROM
#XMLData.nodes('/details/detail') AS xmlData(detail)
END
END
C#:
StringBuilder sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\"?>");
sb.AppendLine("<details>")
foreach(GridViewRow gr in gvActivity.Rows)
{
HiddenField hdRefNo = (HiddenField)gr.FindControl("hdRefNo");
HiddenField hdNotes = (HiddenField)gr.FindControl("hdNotes");
string sRefNo = hdRefNo.value.ToString()=="0" ? null :
hdRefNo.value.ToString();
sb.AppendLine("<detail>");
sb.AppendLine("<ActivityId>"+ gActivityId.ToString() + "</ActivityId>");
if(sRefNo!="0")
sb.AppendLine("<RefNo>"+ sRefNo + "</RefNo>");
else
sb.AppendLine("<RefNo></RefNo>");
sb.AppendLine("<Notes>"+ hdNotes.value.ToString() + "</Notes>");
sb.AppendLine("</detail>");
}
sb.AppendLine("</details>")
You don't need to use query() when fetching values. Use values() directly and you will get NULL if the RefNo node is missing.
detail.value('(RefNo/text())[1]','int') as RefNo
Try using "" instead of null in
string sRefNo = hdRefNo.value.ToString()=="0" ? null :
hdRefNo.value.ToString();
like
string sRefNo = hdRefNo.value.ToString()=="0" ? "":
hdRefNo.value.ToString();
and remove if else part and just keep the statement
sb.AppendLine("<RefNo>"+ sRefNo + "</RefNo>");
In this line
string sRefNo = hdRefNo.value.ToString()=="0" ? null :
hdRefNo.value.ToString();
your checking string and if it equals "0" that assign null, so when you after try checking
if(sRefNo!="0") // this condition always true
sb.AppendLine("<RefNo>"+ sRefNo + "</RefNo>");
else
sb.AppendLine("<RefNo></RefNo>");
Possibly if you change condition to !string.IsNullOrEmpty(sRefNo) it will be work as expected
When you try get int field and in xml it don't set, then here
....
detail.query('RefNo').value('.','int') as RefNo,
....
will be return default value, i.e. 0
for solving you can try use number() function like this
....
detail.query('RefNo').value('number(.)','int') as RefNo,
....
Related
Table creation code for Oracle
CREATE TABLE "STUDENTS"
(
"S_ID" NUMBER NOT NULL ENABLE,
"USERNAME" VARCHAR2(20) NOT NULL ENABLE,
"FULL_NAME" VARCHAR2(25) NOT NULL ENABLE,
"EMAIL" VARCHAR2(40),
"CONTACT_NO" VARCHAR2(25),
"GENDER" NUMBER(1,0),
"STATUS" NUMBER(1,0),
"ADMISSION_DATE" DATE,
"ADMISSION_NO" NUMBER,
"FATHER_NAME" VARCHAR2(25),
"MOTHER_NAME" VARCHAR2(25),
"DATE_OF_BIRTH" DATE,
"NATIONALITY" VARCHAR2(15),
"RELIGION" VARCHAR2(15),
"CLASS_NO" VARCHAR2(5),
"SECTION_NAME" VARCHAR2(10),
"S_ROLL_NO" VARCHAR2(15),
"PASSWORD" VARCHAR2(16) NOT NULL ENABLE,
"GUARDIAN_FULL_NAME" VARCHAR2(25) NOT NULL ENABLE,
"GUARDIAN_CONTACT_NO" VARCHAR2(25) NOT NULL ENABLE,
"GUARDIAN_ADDRESS" VARCHAR2(40) NOT NULL ENABLE,
"PRE_SCHOOL" NUMBER(1,0),
"PRIMARY" NUMBER(1,0),
"MIDDLE" NUMBER(1,0),
"MIDDLE_YEAROFPASS" VARCHAR2(10),
"MIDDLE_INSTITUTION" VARCHAR2(50),
"HIGH_SCHOOL_SSC" NUMBER(1,0),
"SSC_YEAROFPASS" VARCHAR2(10),
"SSC_INSTITUTION" VARCHAR2(50),
"HIGHER_SECONDARY_HSSC" NUMBER(1,0),
"HSSC_YEAROFPASS" VARCHAR2(10),
"HSSC_INSTITUTION" VARCHAR2(50),
"IMAGE" BLOB,
CONSTRAINT "STUDENTS_PK" PRIMARY KEY ("S_ID", "USERNAME") ENABLE
);
ALTER TABLE "STUDENTS"
ADD CONSTRAINT "STUDENTS_SECTION_NAME_FK"
FOREIGN KEY ("SECTION_NAME")
REFERENCES "SECTIONS" ("SECTION_NAME") ENABLE;
Image conversion
FileStream file = new FileStream(imgpath, FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(file);
FileInfo info = new FileInfo(imgpath);
byte[] imgData = br.ReadBytes((int)file.Length);
Student registration...
cmd.Connection = con;
Oracle query to insert into students table
cmd.CommandText = "insert into HRM.students values(:s_id, :username,
:full_name, :email, :contact_no, :gender, :status" +
", :admission_date, :admission_no, :father_name, :mother_name,
:date_of_birth, :nationality, :religion, :class_no, :section_name" +
", :s_roll_no, :password, :guardian_full_name, :guardian_contact_no,
:guardian_address, :pre_school, :primary_school, :middle" +
", :middle_yearofpass, :middle_institution, :high_school_ssc,
:ssc_yearofpass, :ssc_institution, :higher_secondary_hssc" +
", :hssc_yearofpass, :hssc_institution, :image)";
string DOB = usr_DOB.Value.Date.ToString("dd-MMM-yyyy");
Adding parameters, all the specified table parameters are added with the replacing values, can't find out which parameter is causing the error
cmd.Parameters.Add("s_id", GenerateNewID());
The GenerateNewID() method just simply fetches a counter for previous admissions and adds 1 and returns for the newID
cmd.Parameters.Add("username", usr_name.Text);
cmd.Parameters.Add("full_name", usr_fullname.Text);
cmd.Parameters.Add("email", usr_email.Text);
cmd.Parameters.Add("contact_no", usr_contactNo.Text);
cmd.Parameters.Add("gender", genderVal);
cmd.Parameters.Add("status", StatusVal);
Status (enabled / false), gender and some other variables are evaluated to 0 or 1 based on binary conditions where only two options were available.
cmd.Parameters.Add("admission_date", dated);
cmd.Parameters.Add("admission_no", GenerateNewID());
cmd.Parameters.Add("father_name", usr_fathername.Text);
cmd.Parameters.Add("mother_name", usr_mothername.Text);
cmd.Parameters.Add("date_of_birth", DOB);
cmd.Parameters.Add("nationality", usr_nationality.Text);
cmd.Parameters.Add("religion", usr_religion.Text);
cmd.Parameters.Add("class_no", usr_Class.Text);
cmd.Parameters.Add("section_name", usr_assignedSection.Text);
cmd.Parameters.Add("s_roll_no", GenerateNewID());
cmd.Parameters.Add("password", password);
cmd.Parameters.Add("guardian_full_name", usr_GuardianName.Text);
cmd.Parameters.Add("guardian_contact_no", usr_GuardianContactNo.Text);
cmd.Parameters.Add("guardian_address", usr_GuardianFullAddress.Text);
cmd.Parameters.Add("pre_school", preVal);
cmd.Parameters.Add("primary_school", primaryVal);
cmd.Parameters.Add("middle", midVal);
cmd.Parameters.Add("middle_yearofpass", usr_middle_yearOfPass.Text);
cmd.Parameters.Add("middle_institution", usr_middle_insititution.Text);
cmd.Parameters.Add("high_school_ssc", secondaryVal);
cmd.Parameters.Add("ssc_yearofpass", usr_ssc_yearOfPass.Text);
cmd.Parameters.Add("ssc_institution", usr_secondary_insititution.Text);
cmd.Parameters.Add("higher_secondary_hssc", higherSecondaryVal);
cmd.Parameters.Add("hssc_yearofpass", usr_hssc_yearOfPass.Text);
cmd.Parameters.Add("hssc_institution",
usr_HighSecondary_institution.Text);
cmd.Parameters.Add("image", (Object)imgData);
con.Open();
Execution
cmd.ExecuteNonQuery();
con.Close();
Three things:
Like I mentioned in the comment, you don't bind IDs/PKs in an insert statement like that. In the insert instead of :s_id use SEQUENCE_NAME.nextval though you'll want to replace SEQUENCE_NAME with the name of the sequence used to increment the PK value. Since you're executing raw SQL instead of using something like Entity Framework you might have to explicitly reference the sequence. Alternatively, you could try just excluding the ID altogether. I'm not 100% sure so you'll have to test this, but Oracle might do the autoincrementing work for you if you're not referencing it (which in that case it becomes purely preference; personally I like having it explicitly added to the command).
When you're binding parameters with cmd.Parameters.Add("hssc_yearofpass", usr_hssc_yearOfPass.Text); you need to include : in the first parameter (the name of the parameter). So you should have cmd.Parameters.Add(":hssc_yearofpass", usr_hssc_yearOfPass.Text); and do this for all parameters.
It looks like all the parameters for the table are present. Just double check the spelling in addition to my 2nd point.
A table contain bigInt column named 'Phone' I want to insert null value to this column by entity frame work. I used following codes:
objRegister.Phone = Convert.ToInt64(txtPhone.Text ??null );
But i get this message: "Input string was not in a correct format.".
I change the code as shown in below:
objRegister.Phone = txtMobile.Text != null ?Convert.ToInt64(txtMobile.Text):((long?)null) ;
I got same message : "Input string was not in a correct format."
You could try this something like this:
long phone;
objRegister.Phone = long.TryParse(txtPhone.Text, out phone)
? (long?)phone
: (long?)system.DBNullValue;
Int64 phoneNumber;
Int64.TryParse(txtPhone.Text, out phoneNumber) == true ? phoneNumber : DBNull.Value;
You can use ?: Conditional Operator with Int64.TryParse check whether text is convertible to Int64. If convertible then assign convertible value else DBNull.Value
I want a value to be set to NULL if nothing is put into the text box in the form I'm submitting. How can I make this happen?
I've tried inserting 'NULL' but this just adds the word NULL into the field.
I'm not sure what code I should provide for this, I'm just writing an UPDATE query.
Don't put NULL inside quotes in your update statement. This should work:
UPDATE table SET field = NULL WHERE something = something
You're probably quoting 'NULL'. NULL is a reserved word in MySQL, and can be inserted/updated without quotes:
INSERT INTO user (name, something_optional) VALUES ("Joe", NULL);
UPDATE user SET something_optional = NULL;
UPDATE MyTable
SET MyField = NULL
WHERE MyField = ''
You should insert null, not the string of 'NULL'.
Use NULL (without the quotes around it).
UPDATE users SET password = NULL where ID = 4
if (($_POST['nullfield'] == 'NULL') || ($_POST['nullfield'] == '')) {
$val = 'NULL';
} else {
$val = "'" . mysql_real_escape_string($_POST['nullfield']) . "'";
}
$sql = "INSERT INTO .... VALUES ($val)";
if you put 'NULL' into your query, then you're just inserting a 4-character string. Without the quotes, NULL is the actual null value.
Assuming the column allows a null setting,
$mycolupdate = null; // no quotes
should do the trick
The answers given here are good but i was still struggling to post NULL and not zero in mysql table.
Finally i noted the problem was in the insert query that i was using
$quantity= "NULL";
$itemname = "TEST";
So far so good.
My insert query was bad.
mysql_query("INSERT INTO products(quantity,itemname)
VALUES ('$quantity','$itemname')");
I corrected query to read.
mysql_query("INSERT INTO products(quantity,itemname)
VALUES ('".$quantity."','$itemname')");
So the $quantity is outside of the main string.
My sql table now accepted to record null quantity instead of 0
The problem you had is most likely because mysql differentiates between null written in capital letters and null written in small case.
So if you used an update statement with null, it would not work. If you set it to NULL, it would work fine.
Thanks.
I have a table in SQL Server 2008, where for each value id, I have inserted a list of values with comma delimited.
So In the front end, when I select a particular id from the DropDownList, I want to retieve the comma delimited values separately into to a ListBox.
Hope my question is clear. Kindly help...
Try this
//doing this in front end - C#
string values = getValuesFromDB(dropdownList.SelectedValue);
myListBox.DataSource = values.Split(',');
myListBox.DataBind();
OR
foreach(string s in values.Split(','))
{
myListBox.Items.Add(s);
}
There are also answers on SO that shows how to convert CSV to table and am sorry for not asking which SQL database you are using
UPDATE
private string getValuesFromDB(string selectedID)
{
//this might not be the rea; query
string query = "SELECT commaValues FROM myTable WHERE id = " + selectedID;
....
....
string commaSeparatedValues = "retrieved values from this recod";
return commaSeparatedValues;
}
using string split function will give you values in array which you can loop through to assign in list box
pseudo code
string myids = //data retrived from DB
string [] id = myids.split(',') //I assume , as delimiter
//loop thorugh id array and assign it to listbox item.
for(int i=0; i<id.Length; i++)
{
listbox1.items.add(id[i]); //Assuming listbox1 is your Listbox control
}
there could be syntax errors but i think you got the idea.
Below is the example Once data comes in to table then you can easily bind data in to list box.
STEP 1
Execute the following procedure in your Sql Server window.
The fn_CommaSeparatedStringToTable function accepts comma separated string and a value('Y' or 'N') to include NULL and EMPTY strings in the result set
ALTER FUNCTION [dbo].[fn_CommaSeparatedStringToTable]
(
#CommaSeparatedValues VARCHAR(MAX),
#IncludeEmptyStrings CHAR(1)
)
RETURNS #Item TABLE
(
RowId int IDENTITY(1, 1) NOT NULL,
Value VARCHAR(200)
)
AS
BEGIN
DECLARE #IndefOfComma int,
#Value VARCHAR(200),#StartPos bigint,#EndPos
bigint,#LengthOfString int, #ReachedEnd Char(1)
SET #StartPos=1
SET #EndPos=0
SET #LengthOfString=LEN(#CommaSeparatedValues)
SET #ReachedEnd='N'
WHILE #ReachedEnd<>'Y'
BEGIN
SET #EndPos=CHARINDEX(',',#CommaSeparatedValues,#StartPos)
IF #EndPos>0
BEGIN
SET #Value = SUBSTRING(#CommaSeparatedValues, #StartPos,#EndPos-
#StartPos)
SET #StartPos=#EndPos+1
END
ELSE
BEGIN
SEt #ReachedEnd='Y'
SET #Value = SUBSTRING(#CommaSeparatedValues,
#StartPos,#LengthOfString-(#StartPos-1))
END
IF(#Value<>'' OR #IncludeEmptyStrings='Y')
INSERT INTO #Item(Value) VALUES(#Value)
END
RETURN
END
STEP 2
To access the function, use the following query
Include Empty or Null String in the result
SELECT * FROM [dbo].[fn_CommaSeparatedStringToTable]
('ALICE,BRAD,JOHN,JOE,MIC,SCAIF,JEMY, ,','Y')
Do not include Empty or Null String in the result
SELECT * FROM [dbo].[fn_CommaSeparatedStringToTable]
('ALICE,BRAD,JOHN,JOE,MIC,SCAIF,JEMY, ,','N')
Storing the values on this way in the database not a good idea, because:
1: If you want to fill a dropdownlist may you will find the point when you need different id's, like:
1 - First Otion
3 - Second Option
11 - Third Option
Then it is hard to decode just from the values.
2: It always make it much longer to parse them. The storage is not so "expensive", then the processor time, so it is definietly not a good strategy.
However, if you would like to change it or solve it on an SQL level, you can write an SQL Function to parse the delimited string.
An SQL function what is doing something like this, can help:
DECLARE #string varchar(500)
--Here comes the selected one
SELECT #string = Value FROM List WHERE ID = 2
DECLARE #pos int
DECLARE #id int
DECLARE #piece varchar(500)
DECLARE #returnTable table(
ID int,
Value varchar(64)
)
SET #id = 0
IF right(rtrim(#string),1) <> ','
SET #string = #string + ','
SET #pos = patindex('%,%' , #string)
WHILE #pos <> 0
BEGIN
SET #piece = left(#string, #pos - 1)
INSERT INTO #returnTable VALUES(#id, #piece)
SET #id = #id + 1
SET #string = stuff(#string, 1, #pos, '')
SET #pos = patindex('%,%' , #string)
END
SELECT * FROM #returnTable
I have this stored Procedure in MS SQL2008 (C#)
ALTER PROCEDURE UpdateProducts
#ProductID INT, #Name nvarchar(50), #Length Float
AS
UPDATE Product
SET Name = #Name, Length = #Length
WHERE (ProductID = #ProductID)
Length are in some cases "" (nothing). But when "" is inserted the value 0 is inserted instead. I want the value to be null. How can I do that? This did not work:
if (Length == "")
{
Length = null;
}
Set the defaults to NULL in the proc and you dont have to explicity pass NULL to a proc.
CREATE PROC ..dbo.Proc ( #param1 int =NULL, #param2 varchar(40) = NULL ,etc)
Also, if you have to send NULL from your app you would use DBNull.Value
Try DBNull.Value:
if (Size == "")
{
Size = DBNull.Value;
}
and make sure your database column is nullable.
Use NULLIF
UPDATE Product
SET Name = #Name, Length = NULLIF(#Length, '')
WHERE (ProductID = #ProductID)
Empty string is implicitly cast to 0 for float and int. decimal gives an error
Empty string and NULL are different
Edit: this deals with unclean input, so you don't have to worry about it...