在SQL Server中附加image数据类型的二进制数据

时间:2012-06-04 06:47:58

标签: c# asp.net sql-server-2008 sql-server-2005

是否可以将二进制数据附加到SQL Server中数据类型为image的列。 我认为varbinary(max)是可能的,但我想要图像数据类型的解决方案。 如果是,请提供代码示例。

2 个答案:

答案 0 :(得分:1)

首先,正如其他人所说,你应该使用VARBINARY类型而不是IMAGE。

无论如何,如果您仍想使用IMAGE,可以使用UPDATETEXT命令:

DECLARE @Pointer VARBINARY(1);
SELECT @Pointer = TEXTPTR(Data) FROM TableName WHERE Id = @Id;

UPDATETEXT TableName.Data @Pointer @Offset @Delete WITH LOG @Bytes;

考虑:

@Bytes =要追加的实际字节数

@Delete =如果你想删除它在字节位置的内容

答案 1 :(得分:0)

//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();

注意:将在Microsoft SQL Server的未来版本中删除ntext,text和image数据类型。避免在新的开发工作中使用这些数据类型,并计划修改当前使用它们的应用程序。请改用nvarchar(max),varchar(max)和varbinary(max)。