SQL Server表中的RefNo列的数据类型为bigint,并且可以接受Null。 我使用c#通过xml保存多个记录。代码工作正常,但是对于一些记录,RefNo必须为null,即使我在stringbuilder中注释'else'部分,它也保存为0。
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>")
答案 0 :(得分:1)
获取值时无需使用query()
。直接使用values()
,如果RefNo节点丢失,您将获得NULL
。
detail.value('(RefNo/text())[1]','int') as RefNo
答案 1 :(得分:0)
尝试在
中使用""
代替null
string sRefNo = hdRefNo.value.ToString()=="0" ? null :
hdRefNo.value.ToString();
喜欢
string sRefNo = hdRefNo.value.ToString()=="0" ? "":
hdRefNo.value.ToString();
并删除if else部分并保留声明
sb.AppendLine("<RefNo>"+ sRefNo + "</RefNo>");
答案 2 :(得分:0)
在这一行
string sRefNo = hdRefNo.value.ToString()=="0" ? null :
hdRefNo.value.ToString();
你的检查字符串,如果它等于分配null
的“0”,那么当你尝试检查
if(sRefNo!="0") // this condition always true
sb.AppendLine("<RefNo>"+ sRefNo + "</RefNo>");
else
sb.AppendLine("<RefNo></RefNo>");
如果您将条件更改为!string.IsNullOrEmpty(sRefNo)
,它可能会按预期工作
当你尝试获取int
字段时,在xml中它没有设置,那么
....
detail.query('RefNo').value('.','int') as RefNo,
....
将返回默认值,即0
要解决此问题,您可以尝试使用number()
这样的功能
....
detail.query('RefNo').value('number(.)','int') as RefNo,
....