2

I want to do some testing of a SQL CLR procedure and I'm trying to replicate it in a local C# project for better debugging.

I need to convert the data returned from the database to SqlBytes in order for my C# function to accept it but it tells me that I can't implicitly convert it. Note that the SQL column is of type image.

Code:

        SqlConnection con = new SqlConnection(connString);
        SqlDataAdapter da = new SqlDataAdapter(query, con); //query gets a field from the database of type 'image'
        SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
        DataSet ds = new DataSet("Image");
        byte[] MyData = new byte[0];
        da.Fill(ds, "Image");
        DataRow myRow;
        myRow = ds.Tables["Image"].Rows[0];

        MyData = (byte[])myRow["econtents"];
        SqlBytes SQL = (SqlBytes)MyData; //Cannot implicitly convert type 'byte[]' to 'System.Data.SqlTypes.SqlBytes'

I've tried a few different options/syntaxes for the last line and also just passing MyData into the method directly.

I've been following this Microsoft article but it's not quite the same as my scenario. For reference I want to pass the data returned from the SQL query to: public static SqlString WriteToFile(SqlBytes binary, SqlString path, SqlBoolean append)

How do I perform this conversion, or is it only possible to pass in SqlBytes when using a CLR function from the SQL side?

1
  • The image datatype has been deprecated in favor of varbinary (max) for more than a decade now. Commented Mar 12, 2018 at 16:34

1 Answer 1

4

It's quite simple - you pass your byte array to the overloaded SqlBytes constructor:

var bytes = new byte[] { 1, 2, 3 };
var sqlBytes = new SqlBytes(bytes);

This constructor "initializes a new instance of the SqlBytes class based on the specified byte array".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.