Is it possible to append binary data to column whose datatype is image in SQL server. I herad it's possible for varbinary(max),but i want solution for image datatype. If so,please provide me the code sample.
2 Answers
First, as others have said, you should use VARBINARY type instead of IMAGE.
Anyway, if you still want to use IMAGE, you can use UPDATETEXT command like this:
DECLARE @Pointer VARBINARY(1);
SELECT @Pointer = TEXTPTR(Data) FROM TableName WHERE Id = @Id;
UPDATETEXT TableName.Data @Pointer @Offset @Delete WITH LOG @Bytes;
Consider:
@Bytes = the actual bytes you want to append
@Delete = if you want to delete what it may have in its bytes positions
Comments
//Create Binary Data Stream
string filePath = Server.MapPath("APP_DATA/TestDoc.docx");
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
--------------------
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
SqlCommand cmd = new SqlCommand(strQuery,conn);
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
cmd.ExecuteNonQuery();
Note: ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
3 Comments
ravidev
i don't want to insert,but i want to append/update to existing binary data like .WRITE method for VARBINARY(MAX)
Romil Kumar Jain
You can overwrite but can't append
Romil Kumar Jain
Use the Update sql statement instead of Select sql statement in strQuery variable.
IMAGEhas been deprecated - you should always useVARBINARY(MAX)instead.