Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error trying to execute sql from inside SQL CLR

Tags:

sqlclr

I have the following code:

[SqlFunction(DataAccess = DataAccessKind.Read, SystemDataAccess = SystemDataAccessKind.Read)]
    public static int GetInt()
    {
        int retValue = 0;
        using (SqlConnection conn = new SqlConnection("context connection = true"))
        {
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select MyInt from SomeTable";
            object timeOut = cmd.ExecuteReader(); // <- error happen here

        }
        return retValue;

    }

I get the following exception in

cmd.ExecuteReader();

{"This statement has attempted to access data whose access is restricted by the assembly."}

like image 377
Pacman Avatar asked Mar 29 '13 22:03

Pacman


People also ask

What is CLR in SQL database?

NET Framework common language runtime (CLR) manages and secures access between different types of CLR and non-CLR objects running within SQL Server. These objects may be called by a Transact-SQL statement or another CLR object running in the server. For more detailed information, see CLR Integration Security.

What is CLR stored procedure in SQL Server?

Stored procedures are routines that cannot be used in scalar expressions. They can return tabular results and messages to the client, invoke data definition language (DDL) and data manipulation language (DML) statements, and return output parameters.

Why do we use CLR?

The Common Language Runtime (CLR) is programming that manages the execution of programs written in any of several supported languages, allowing them to share common object-oriented classes written in any of the languages. It is a part of Microsoft's . NET Framework.


2 Answers

As a side note, if you're trying to access temporary tables created with #, such as #tmp, you need to also put in SystemDataAccess = SystemDataAccess.Read. Another way around this would be to use a common table expression to get your data.

like image 101
Derreck Dean Avatar answered Sep 21 '22 12:09

Derreck Dean


I needed to add DataAccess = DataAccess.Read to the function attribute in order to do that.

like image 21
Pacman Avatar answered Sep 20 '22 12:09

Pacman