Click here to Skip to main content
15,886,736 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Problem
I work on sql server 2012 when implement clr function i get error
Msg 6522, Level 16, State 1, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "spExecuteParallel": 
System.NullReferenceException: Object reference not set to an instance of an object.
System.NullReferenceException: 
   at SqlStoredProcedureClr.spExecuteParallel(String DB, Int32 MaxDOP, String TSQL, Int32 msDelay, Int32 Retries)
.

it is actually executed one time only for insert and insert data but after that error above display
select dbo.spExecuteParallel
( N'Test',8, N'Insert into TestTable (messagesData, LogDateValues) values (''Test'', GetDate())', 0, 1)


function sql clr is
Create FUNCTION [dbo].[spExecuteParallel](@DB [nvarchar](200), @MaxDOP [int], @TSQL [nvarchar](4000), @msDelay [int], @Retries [int])
RETURNS [bigint] WITH EXECUTE AS CALLER, RETURNS NULL ON NULL INPUT
AS 
EXTERNAL NAME [StoredProcedures].[SqlStoredProcedureClr].[spExecuteParallel]


What I have tried:

public static class SqlStoredProcedureClr
{
 
        [SqlFunction(SystemDataAccess = SystemDataAccessKind.Read, DataAccess = DataAccessKind.Read)]
        public static SqlInt64 spExecuteParallel(string DB, int MaxDOP, string TSQL, int msDelay, int Retries)
        {
            // Initialize Variables
            SqlConnection oConn = new SqlConnection();
            SqlCommand oCmd = new SqlCommand();
            List<string> oErrorString = new List<string>();
            object oLocker = new object();
            string sServer = null;

            List<Thread> oThread = new List<Thread>();
            StringCollection sStopped = new StringCollection();

      
    
        oConn = new SqlConnection("context connection = true;");
        oConn.Open();

            oCmd = oConn.CreateCommand();
            oCmd.CommandText = "SELECT @@SERVERNAME";
            sServer = oCmd.ExecuteScalar().ToString();

            oCmd.Dispose();
            oConn.Close();
            oConn.Dispose();

            // Execute Threads
            int iCurrentThread = 0;
            while (iCurrentThread < MaxDOP)
            {
                ExecuteSQL Executer = new ExecuteSQL
                (sServer, DB, TSQL.Replace("?", DB.ToString().Trim()), Retries, ref oErrorString, ref oLocker);

                Thread oItem = new Thread(Executer.Process);
                oItem.Name = "ExecuteSQL " + DB.ToString().Trim();
                oItem.Start();
                oThread.Add(oItem);

            SqlContext.Pipe.Send(DateTime.Now.ToLongTimeString() +
            " : Start : " + oItem.Name.Replace("ExecuteSQL ", ""));
            Thread.Sleep(msDelay);

                while (RunningThreads(ref oThread, ref sStopped) >= MaxDOP)
                {
                    Thread.Sleep(1000);
                }
                iCurrentThread++;
            }

            // Wait for all Threads to Stop
            while (RunningThreads(ref oThread, ref sStopped) > 0)
            {
                Thread.Sleep(1000);
            }
            SqlContext.Pipe.Send("All Thread have Stopped with " +
            oErrorString.Count.ToString() + " Error/s ");
         
            if (oErrorString.Count > 0)
            {
            try
            {
                foreach (string sIndividualErrors in oErrorString)
                {
                    SqlContext.Pipe.Send(sIndividualErrors.ToString());
                }
            }
            catch (Exception ex)
            {
                ex.ToString();

            }

                throw new Exception("Error Occurred.");
            }

            return 0 - oErrorString.Count;
        }

        public static int RunningThreads(ref List<Thread> oThread, ref StringCollection oStops)
        {
            int iRunningCount = 0;

            foreach (Thread oIndividualThread in oThread)
            {
                if (oIndividualThread.IsAlive)
                {
                    iRunningCount += 1;
                }
                else if (!oStops.Contains(oIndividualThread.Name))
                {
                    oStops.Add(oIndividualThread.Name);
                   SqlContext.Pipe.Send(DateTime.Now.ToLongTimeString() + " : Stop  :  " + oIndividualThread.Name.Replace("ExecuteSQL ", ""));


                }
            }
            return iRunningCount;
        }
    }
class ExecuteSQL
    {

        private List<string> oExecuteErrors;
        private object oExecuteLocker;
        private string sExecuteServer;
        private string sExecuteDB;
        private string sExecuteTSQL;
        private int iExecuteRetries;

        public ExecuteSQL(string sServer, string sDB, string sTSQL,
        int iRetries, ref List<string> oErrors, ref object oLocker)
        {
            this.sExecuteServer = sServer;
            this.sExecuteDB = sDB;
            this.sExecuteTSQL = sTSQL;
            this.iExecuteRetries = iRetries;
            this.oExecuteErrors = oErrors;
            this.oExecuteLocker = oLocker;
        }

        public void Process()
        {
            int iTries = 1;
            SqlConnection oConn = new SqlConnection();

        Retry:
            oConn = new SqlConnection("Data Source=" + sExecuteServer +
            ";Initial Catalog=" + sExecuteDB + ";Integrated Security=SSPI;");
            try
            {
                oConn.Open();

                if (oConn.State == ConnectionState.Open)
                {
                    SqlCommand oCmd = oConn.CreateCommand();
                    oCmd.CommandText = sExecuteTSQL;
                    oCmd.CommandTimeout = 0;
                    oCmd.ExecuteNonQuery();

                    oCmd.Dispose();
                    oConn.Close();
                    oConn.Dispose();
                }
                else
                {
                    throw new Exception("SQL Server not Found or Unable to Connect to SQL Server");
                }
            }
            catch (Exception ex)
            {
                if (oConn.State != ConnectionState.Closed) oConn.Close();
                oConn.Dispose();

                if (iTries <= iExecuteRetries)
                {
                    Thread.Sleep(5000);
                    iTries += 1;
                    goto Retry;
                }
                else
                {
                    lock (oExecuteLocker)
                    {
                        char cSpace = char.Parse(" ");
                        oExecuteErrors.Add(this.sExecuteDB.PadRight(16, cSpace) + " : " + ex.Message);
                    }
                }
            }
        }
Posted
Updated 5-Nov-19 6:58am

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
You can debug Code in SQL Server, but if you don't know how here's an alternative:
Simply add a counter to your procedure and a try catch block to see where the error occurs:

int i;
  i = 0;
  try
  {

      i = 1;
      ...some code
      i = 2;
      .
      .
      .
      i=3
  }
  catch
  {
      throw new Exception("Error at " + i.ToString());
  }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900