views:

50

answers:

1

I want to use CLR table-valued function in SQL Server 2008, which accesses a database from inside itself. I've got a permission exception. I am trying to execute function as the same user as under which it was created. So cause of the problem is not clear..

Here is the function:

public partial class MyClass
    {    
        [SqlFunction(
            DataAccess = DataAccessKind.Read,
            FillRowMethodName = "Availability_FillRow",
            TableDefinition = "B0RID nchar(32)")]
        public static IEnumerable Fn_SEARCH_Availability(SqlDateTime checkin, SqlInt32 overnights)
        {
            if (checkin.IsNull || overnights.IsNull)
            {
                return null;
            }
            List<ResultRoom> roomsResultList = new List<ResultRoom>();


        using (SqlConnection conn = new SqlConnection("Data Source=MachineName;Initial Catalog=DBNANE;Integrated Security=True"))
        {
            conn.Open();
        }
        return roomsResultList;
    }
}

Here is the exception

A .NET Framework error occurred during execution of user-defined routine or aggregate "Fn_SEARCH_Availability": 
System.Security.SecurityException: Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
System.Security.SecurityException: 
   at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
   at System.Security.PermissionSet.Demand()
   at System.Data.Common.DbConnectionOptions.DemandPermission()
   at System.Data.SqlClient.SqlConnection.PermissionDemand()
   at System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.SqlClient.SqlConnection.Open()
   at StoredProcedures.Fn_SEARCH_Availability(SqlDateTime checkin, SqlInt32 overnights)
+2  A: 

Maybe try changing the using statement that establishes the connection to

using (SqlConnection conn = new SqlConnection("context connection=true;"))

Which tells the CLR to use the current SQL connection.

My guess for why yours failed is that by specifying Integrated security it would be using the credentials of the SQL Server Service account.

More info on this here

TooFat
Thanks, that was the right answer
Tim