我在SQL中使用了列Employee
和Id(bigint)
的表DocumentContent(varbinary(MAX))
。
现在,当我尝试使用XML在Employee
表中插入记录时,Null
值存储在表中,用于大小小于1Kb
的文件。当文件大小大于1Kb
时,它将被转换为二进制数据并存储在数据库中。
我生成的XML如下:
<MyDocuments>
<Rows>
<Id>62</Id>
<Document_Content>104116116112584747495550464954464846495856485748471041161161129910810510111011646104116109108</Document_Content>
</Rows>
</MyDocuments>
和存储过程是
CREATE Procedure [dbo].[Proc_SaveDocuments]
(
@XMLData as XML
)
AS
BEGIN
Declare @propertyCount Varchar(100) = '',@currentCount int=1,@Id bigint,@Content varbinary(MAX)
SELECT @propertyCount = convert(VARCHAR, @XMLData.query ('count(/MyDocuments/Rows)'))
SET @currentCount = 1
WHILE (@currentCount<=@propertyCount)
BEGIN
SET @Id = @XMLData.value('data(/MyDocuments/Rows[sql:variable("@currentCount")]/Id)[1]', 'BIGINT')
SET @Content = @XMLData.value('data(/MyDocuments/Rows[sql:variable("@currentCount")]/Document_Content)[1]', 'VARBINARY(MAX)')
insert into Employee values(@Id,@Content) --inserts null in DocumentContent column when file size less than 1Kb, else converts it to binary and saves it in database.
SET @currentCount = @currentCount + 1
END
END
任何想法为什么会发生这种情况以及如何解决这个问题?
答案 0 :(得分:0)
我假设XML不理解“VARBINARY”格式:
DECLARE @XMLData XML = '<MyDocuments>
<Rows>
<Id>62</Id>
<Document_Content>104116116112584747495550464954464846495856485748471041161161129910810510111011646104116109108</Document_Content>
</Rows>
<Rows>
<Id>63</Id>
<Document_Content>654654654654546847435483797123954898327987329759873256327864929347623974311011646104116109108</Document_Content>
</Rows>
</MyDocuments>'
Declare @propertyCount Varchar(100) = '',@currentCount int=1,@Id bigint,@Content varbinary(MAX)
SELECT @propertyCount = convert(VARCHAR, @XMLData.query ('count(/MyDocuments/Rows)'))
SET @currentCount = 1
SELECT @propertyCount = convert(VARCHAR, @XMLData.query ('count(/MyDocuments/Rows)'))
SET @currentCount = 1
WHILE (@currentCount<=@propertyCount)
BEGIN
SET @Id = @XMLData.value('data(/MyDocuments/Rows\[sql:variable("@currentCount")\]/Id)\[1\]', 'BIGINT')
SET @Content = CAST(@XMLData.value('data(/MyDocuments/Rows\[sql:variable("@currentCount")\]/Document_Content)\[1\]', 'VARCHAR(MAX)') as VARBINARY(MAX))
SET @currentCount += 1
SELECT @Id,@Content
END]