Quantcast
Channel: .NET Framework inside SQL Server forum
Viewing all 780 articles
Browse latest View live

System.Data.SqlClient.SqlException: The locale identifier (LCID) 16393 is not supported by SQL Server

$
0
0

I have SQL Server 2005 Developer Edition. And my operating system is Windows Vista.

 

I have written a procedure in C# and deployed it on SQL Server. However when i try to run it i get the following error.

System.Data.SqlClient.SqlException: The locale identifier (LCID) 16393 is not supported by SQL Server

 

Also I tried using same procedure in Windows XP machine and it workd fine. Can anyone help me what could be the problem?


How to resolve that install both sql server 2005 and 2008R2 in same machine ?

$
0
0
I have installed Sql server 2005 in my machine which has Windows 7  that has successfully installed and working fine.

Coming to point I want to install Sql server 2008 R2 for another project in the same machine,
But when I try to install Sql server 2008 R2  at the time of  final stage the message box displaying with  this Installation Rules “Sql server 2005 Express tools Failed” and "Previous releases of MS Visual Studio 2008 - failed".

So my requirement is I need 2005 and as well as 2008 R2 both are used for different purposes for that how to maintain both versions in single machine?
Is it possible that both should maintain in single machine?

Please suggest me how can I handle this problem. Your valuable suggestion is very helpful to me.

System.Data.SqlClient.SqlException: The locale identifier (LCID) 16393 is not supported by SQL Server

$
0
0

I have SQL Server 2005 Developer Edition. And my operating system is Windows Vista.

 

I have written a procedure in C# and deployed it on SQL Server. However when i try to run it i get the following error.

System.Data.SqlClient.SqlException: The locale identifier (LCID) 16393 is not supported by SQL Server

 

Also I tried using same procedure in Windows XP machine and it workd fine. Can anyone help me what could be the problem?

Improving CLR performance in SQL Server (redux)

$
0
0

I have been spending a lot of time trying to eek out the maximum performance out of a C# CLR UDF. I have already set IsDeterministic and IsPrecise to true, as well as SystemDataAccessKind.None and DataAccessKind.None.

I am now experimenting with the overhead of transferring to CLR.  I created a simple CLR UDF that just returns the input value, e.g.,

[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic=true, IsPrecise=true)]
public static SqlString MyUDF(SqlString data)
{
	return data;
}

Defined as:

CREATE FUNCTION dbo.MyUDF(@data nvarchar(4000)) RETURNS nvarchar(4000) WITH EXECUTE AS CALLER 
AS EXTERNAL NAME [MyAssembly].[UserDefinedFunctions].[MyUDF];

I then use the UDF in a View on the Primary Key (nvarchar) of a table with about 6M rows.

I know there is a small overhead going through a View versus a Table. However, when I query through the table, it is about 2000% faster than querying through the View with the CLR UDF.  E.g., 3 seconds for the table and 60 seconds for the view! I checked the Query Plans for each and they are both using Parallelization.

I have to assume that all the overhead is in the transition to CLR.  Is that much overhead to be expected?  Is there any way to improve that?

Incidentally, this is a followup to this question:
http://stackoverflow.com/questions/24722708/sql-server-clr-udf-parallelism-redux


Get Server Name from CLR without making a SQL query?

$
0
0

Is there a way to get the current Server Name (essentially @@SERVERNAME or @@SERVICENAME) inside a CLR C# procedure without connecting and making a query to the instance?

Right now it opens a connection using "context connection=true" and makes this query:

    SELECT @@SERVERNAME

However, is there a global property of some sort that has that information already?

Thanks.

SqlContext.WindowsIdentity call throwing exception Data Access is not Allowed

$
0
0

I am having a problem with SQL-CLR impersonation.

SQL Server 2012 on Windows 2008 R2, 64-bit.

C# code line is:

WindowsIdentity CallerIdentity = SqlContext.WindowsIdentity;

Exception thrown:

Msg 6522, Level 16, State 1, Line 2
A .NET Framework error occurred during execution of user-defined routine or aggregate "GetFile": 
System.InvalidOperationException: Data access is not allowed in this context.  Either the context is a function or method not marked with DataAccessKind.Read or SystemDataAccessKind.Read, is a callback to obtain data from FillRow method of a Table Valued Function, or is a UDT validation method.
System.InvalidOperationException: 
   at System.Data.SqlServer.Internal.ClrLevelContext.CheckSqlAccessReturnCode(SqlAccessApiReturnCode eRc)
   at System.Data.SqlServer.Internal.ClrLevelContext.GetCurrentContext(SmiEventSink sink, Boolean throwIfNotASqlClrThread, Boolean fAllowImpersonation)
   at Microsoft.SqlServer.Server.InProcLink.GetCurrentContext(SmiEventSink eventSink)
   at Microsoft.SqlServer.Server.SmiContextFactory.GetCurrentContext()
   at Microsoft.SqlServer.Server.SqlContext.get_WindowsIdentity()
   at SingleFileLoader.SingleFileLoaderHelper()
   at SingleFileLoader..ctor(String FileName)
   at FileAccess.GetFile(String FileName)

This is the code I am running see link below, it is something that was coded by one of the SQL Server folks Balaji Rathakrishnan so it should work "as is" but for me it does not work.

http://blogs.msdn.com/b/sqlclr/archive/2005/05/05/415034.aspx

My database is marked Trustworthy, CLR is enabled, other SQL-CLR code works, only impersonation code fails.

If I comment out the impersonation code then the rest of the code works fine - albeit under service account credentials only.

Any ideas why impersonation is not working from SQL-CLR?

The SQL Server service is running as a "local system", not sure if service must run as a regular Windows Domain account for impersonation to work from SQL-CLR.

Altering function to use Execute as Caller or as Owner does not change anything, same error is received.

Clearly there is some documentation that I have overlooked but I am unable to find it, the impersonation part of Windows seems to work by some sort of magic! 8^)

Thanks in advance

Yuri Budilov


Yuri Budilov

ExecuteReader kills CLR Trigger

$
0
0

I've tried numerous solutions for this issue and all have failed. I need to insert a new record in database b when a record is updated in database a. I've been able to track it down to the ExecuteReader() call. I plan on using a linked server when I get the basic code written but copying the basic example from the sql server 2012 msdn CLR Trigger doc I get this error:

My Code:

 [SqlTrigger(Name = @"CustomerAddEdit", Target = "[db1].[CLIENT]", Event = "FOR INSERT, UPDATE, DELETE")]
    public static void CustomerAddEdit()
    {
        SqlPipe pipe = SqlContext.Pipe;
        try
        {
            pipe.Send("Test");
                SqlTriggerContext triggContext = SqlContext.TriggerContext;
                SqlDataReader reader;
                SqlConnection connection = new SqlConnection(@"context connection=true");
                switch (triggContext.TriggerAction)
                {
                    case TriggerAction.Insert:


                        using (SqlCommand command = new SqlCommand())
                        {
                            connection.Open();
                            command.Connection = connection;
                            command.CommandText = @"SELECT * FROM INSERTED";

                            pipe = SqlContext.Pipe;
                            reader = command.ExecuteReader();

                            string msg = "Values: ";

                            reader.Read();
                            for (int columnNumber = 0; columnNumber < triggContext.ColumnCount; columnNumber++)
                            {
                                msg += string.Format("{0} : {1}\r\n", reader.GetName(columnNumber), triggContext.IsUpdatedColumn(columnNumber).ToString());
                            }
                            pipe.Send("You inserted: " + msg);
                            reader.Close();
                        }
                        break;
                    case TriggerAction.Update:
                        using (SqlCommand command = new SqlCommand())
                        {
                            connection.Open();
                            command.Connection = connection;
                            command.CommandText = @"SELECT * FROM INSERTED";

                            pipe = SqlContext.Pipe;
                            reader = command.ExecuteReader();

                            string msg = "Values: ";

                            reader.Read();
                            for (int columnNumber = 0; columnNumber < triggContext.ColumnCount; columnNumber++)
                            {
                                msg += string.Format("{0} : {1}\r\n", reader.GetName(columnNumber), triggContext.IsUpdatedColumn(columnNumber).ToString());
                            }
                            pipe.Send("You inserted: " + msg);
                            reader.Close();

                        }
                        break;
                }
 
        }
        catch (Exception ex)
        {
            //pipe.Send(ex.Message);
        }
        finally
        {
        }
    }
I've been selling this idea up the chain for sometime and this is really an annoying and possibly deadly roadblock to hit so soon. Never had this problem on previous CLR SP implementations.

Also, any code examples on writing to a text file from a trigger. You can't use impersonate when accessing the context and that is the only way I know how to write to a text file from inside a CLR trigger.

Thanks!

BubbaRichard



public static variables inside C# CLR assembly getting reinitialized

$
0
0

I have a C# CLR DLL that is initialized by EXEC init_myassebly

In it I set several global variables that are declared like this:

static class _Global
{
    public static int g_var1;
    public static string g_var2;
	... etc ...
}

I notice that every so often, these variables seem to get re-initialilized, almost as if SQL Server is automatically unloading and reloading the assembly. Does SQL Server do this? I.e., periodically unload and reload an assembly as needed?  If so, is there a way to keep it permanently loaded until explicitly released?

SELECT from table INSERTED throws exception "There is no row at position 0"

$
0
0

Hi everybody. I've got a problem with a CLR Trigger developed in Visual Studio 2010 and then deployed in SQL Server 2012.

The trigger fires FOR INSERT, UPDATE and so i have a structure like this in my trigger:

...

//TriggerManager is a class that handle the execution of //queries and the trigger context connection using (TriggerManager t = new TriggerManager()) { inserted = @"SELECT * FROM INSERTED"; DataSet lastdoc = new DataSet(); using (SqlCommand cmd = new SqlCommand(inserted)) {

//The method QueryDataAdapter return a dataset filled with the command cmd. lastdoc = t.QueryDataAdapter(cmd); } //Here i need to store the whole record to use it in //further elaborations. //And here the execption is raised. DataRow insertedRow = lastdoc.Tables[0].Rows[0]; int docid = (int)insertedRow["field1"]; string obj = insertedRow["field2"].ToString(); switch (triggerContext.TriggerAction) { case TriggerAction.Insert: ... break; case TriggerAction.Update: ... break; }

So the problem is that the trigger fires, tries to get the Row[0], but the exeption message is "There is no Row at position 0". But the strange things is that the operations which should be executed by the trigger, are executed anyway (and the DataRow inserted row is necessary for the elaboration).

I tryed to insert a control like 

if (lastdoc.Tables.Count >0 && lastdoc.Tables[0].Rows.Count >0)
{
    ...
}

before trying to get the row. But with this control the trigger doesn't perform its operations.

I suppose that the trigger fires again after the failure, but why does it find the table INSERTED empty at the first try ?

after new server migration the assemblies want work anymore

$
0
0

hello everyone

in the old envirement the server is using sql 2008 R2 as well as the new server.

I just made some DB changes to the assemblies and made a new signature from untrust to trust assemblies.  now i getting the following error:

Msg 6522, Level 16, State 1, Procedure sp_HRimport, Line 0
A .NET Framework error occurred during execution of user-defined routine or aggregate "sp_HRimport": 
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.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.SqlClient.SqlConnection.Open()
   at StoredProcedures.import()
.
(1 row(s) affected)

I have no clue how to solve this problem or what the problem is.

I set THRUSTWORTHY to ON and it didnt helped.

the .net code looks like that. I know it isn't the best code but it is working since years

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Collections.Generic;
using System.Text;
public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static int import()
    {
        int ret = 1;
        SqlConnection connection = new SqlConnection("Data Source=SERVERNAME\\instanzename,PORT;Initial Catalog=AdventureWorks;Integrated Security=True");
        // Öffnen der connection
        connection.Open();
        // Holt den Pfad aus der Tabelle system_ZZDB und convertiert es in einen String. Direkte zuweisung wird nicht zugelasen
        SqlCommand command = new SqlCommand("SELECT RTRIM(sys_value) FROM system_ZZDB WHERE sys_key = 'hrPath';", connection);
        String fileName = Convert.ToString(command.ExecuteScalar());
        // Pfad für das PIAS File für Bixi
        string new_path = "\\\\ServerForTheNewPath\\Galaxy$\\pias\\PIAS.TXT";
        // Wen das File vorhanden ist 
        if (File.Exists(fileName))
        {
            // Text hinzufügen zum File
            System.IO.StreamWriter file = new System.IO.StreamWriter(new_path, true, Encoding.GetEncoding(1252));
            FileStream logFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            StreamReader logFileReader = new StreamReader(logFileStream, System.Text.Encoding.Default);
            while (!logFileReader.EndOfStream)
            {
                string line = logFileReader.ReadLine();
                string sql = "INSERT INTO temp_person(per_nummer, per_pid, per_name, per_vname, per_geburtstag, per_sprache, per_anrede, per_buIDHauptort, per_bankstelleHauptort, per_instrAbHauptort, per_instrBisHauptort, per_kostenstelleNrHauptort, per_kostenstelleBezHauptort, per_instradierungHauptort, per_buIDEinsatz, per_bankstelleEinsatz, per_einsatzortAb, per_einsartortBis, per_kostenstelleNrEinsatz, per_kostenstelleBezEinsatz, per_instradierungEinsatz, per_kategorie, per_gebnr, per_telEx, per_eintrittsdatum, per_austrittsdatum, per_letzterArbeitstag, per_pidAlt, per_pidStatus, per_reserve, per_email, per_quelle, per_importDatum, per_isActive, per_key)"+ "VALUES(@per_nummer, @per_pid, @per_name, @per_vname, @per_geburtstag, @per_sprache, @per_anrede, @per_buIDHauptort, @per_bankstelleHauptort, @per_instrAbHauptort, @per_instrBisHauptort, @per_kostenstelleNrHauptort, @per_kostenstelleBezHauptort, @per_instradierungHauptort, @per_buIDEinsatz, @per_bankstelleEinsatz, @per_einsatzortAb, @per_einsartortBis, @per_kostenstelleNrEinsatz, @per_kostenstelleBezEinsatz, @per_instradierungEinsatz, @per_kategorie, @per_gebnr, @per_telEx, @per_eintrittsdatum, @per_austrittsdatum, @per_letzterArbeitstag, @per_pidAlt, @per_pidStatus, @per_reserve, @per_email, @per_quelle, @per_importDatum, @per_isActive, @per_key)";
                SqlCommand cmd = new SqlCommand(sql, connection);
                cmd.Parameters.AddWithValue("@per_nummer", isNull(line.Substring(0, 7)));
                cmd.Parameters.AddWithValue("@per_pid", isNull(line.Substring(7, 7)));
                cmd.Parameters.AddWithValue("@per_name", isNull(line.Substring(14, 20)));
                cmd.Parameters.AddWithValue("@per_vname", isNull(line.Substring(34, 15)));
                //cmd.Parameters.AddWithValue("@per_geburtstag", line.Substring(49, 8));
                cmd.Parameters.AddWithValue("@per_geburtstag", stringToDate(line.Substring(49, 8)));
                cmd.Parameters.AddWithValue("@per_sprache", isNull(line.Substring(57, 1)));
                cmd.Parameters.AddWithValue("@per_anrede", isNull(line.Substring(58, 1)));
                cmd.Parameters.AddWithValue("@per_buIDHauptort", isNull(line.Substring(59, 4)));
                cmd.Parameters.AddWithValue("@per_bankstelleHauptort", isNull(line.Substring(63, 4)));
                //cmd.Parameters.AddWithValue("@per_instrAbHauptort", line.Substring(67, 8));
                cmd.Parameters.AddWithValue("@per_instrAbHauptort", stringToDate(line.Substring(67, 8)));
                //cmd.Parameters.AddWithValue("@per_instrBisHauptort", line.Substring(75, 8));
                cmd.Parameters.AddWithValue("@per_instrBisHauptort", stringToDate(line.Substring(75, 8)));
                cmd.Parameters.AddWithValue("@per_kostenstelleNrHauptort", isNull(line.Substring(83, 3)));
                cmd.Parameters.AddWithValue("@per_kostenstelleBezHauptort", isNull(line.Substring(86, 4)));
                cmd.Parameters.AddWithValue("@per_instradierungHauptort", isNull(line.Substring(90, 10)));
                cmd.Parameters.AddWithValue("@per_buIDEinsatz", isNull(line.Substring(100, 4)));
                cmd.Parameters.AddWithValue("@per_bankstelleEinsatz", isNull(line.Substring(104, 4)));
                //cmd.Parameters.AddWithValue("@per_einsatzortAb", line.Substring(108, 8));
                cmd.Parameters.AddWithValue("@per_einsatzortAb", stringToDate(line.Substring(108, 8)));
                //cmd.Parameters.AddWithValue("@per_einsartortBis", line.Substring(116, 8));
                cmd.Parameters.AddWithValue("@per_einsartortBis", stringToDate(line.Substring(116, 8)));
                cmd.Parameters.AddWithValue("@per_kostenstelleNrEinsatz", isNull(line.Substring(124, 3)));
                cmd.Parameters.AddWithValue("@per_kostenstelleBezEinsatz", isNull(line.Substring(127, 4)));
                cmd.Parameters.AddWithValue("@per_instradierungEinsatz", isNull(line.Substring(131, 10)));
                cmd.Parameters.AddWithValue("@per_kategorie", isNull(line.Substring(141, 2)));
                cmd.Parameters.AddWithValue("@per_gebnr", isNull(line.Substring(143, 6)));
                cmd.Parameters.AddWithValue("@per_telEx", isNull(line.Substring(149, 17)));
                //cmd.Parameters.AddWithValue("@per_eintrittsdatum", line.Substring(166, 8));
                cmd.Parameters.AddWithValue("@per_eintrittsdatum", stringToDate(line.Substring(166, 8)));
                //cmd.Parameters.AddWithValue("@per_austrittsdatum", line.Substring(174, 8));
                cmd.Parameters.AddWithValue("@per_austrittsdatum", stringToDate(line.Substring(174, 8)));
                //cmd.Parameters.AddWithValue("@per_letzterArbeitstag", line.Substring(182, 8));
                cmd.Parameters.AddWithValue("@per_letzterArbeitstag", stringToDate(line.Substring(182, 8)));
                cmd.Parameters.AddWithValue("@per_pidAlt", isNull(line.Substring(190, 7)));
                cmd.Parameters.AddWithValue("@per_pidStatus", isNull(line.Substring(197, 1)));
                cmd.Parameters.AddWithValue("@per_reserve", isNull(line.Substring(198, 6)));
                cmd.Parameters.AddWithValue("@per_email", isNull(line.Substring(204, 78)));
                cmd.Parameters.AddWithValue("@per_quelle", "HR");
                cmd.Parameters.AddWithValue("@per_importDatum", DateTime.Now);
                cmd.Parameters.AddWithValue("@per_isActive", checkAustritt(line.Substring(174, 8)));
                cmd.Parameters.AddWithValue("@per_key", isNull(line.Substring(284, 40)));
                cmd.ExecuteNonQuery();
                // File schreiben für Bixi
                file.WriteLine(line.Substring(0, 284));
            }
            // Schliessen des Files für Bixi
            file.Close();
            // Clean up
            connection.Close();
            logFileReader.Close();
            logFileStream.Close();
            //  Rename File
            File.Copy(fileName, fileName.Substring(0, (fileName.Length - 4)) + "_imported.bak", true);
            // Das File muss gelöst werde, damit die stündlichi Prozedur nur einmal ausgeführt wird
            File.Delete(fileName);
        }
        else
        {
            ret = 0;
        }
        return ret;
    }   //  end method
    //  Methode prüft ob ein String leer ist
    //  Wenn JA wird NULL für die DB zurückgegeben, sonst der Text
    private static Object isNull(String pText)
    {
        Object ret = DBNull.Value;
        if (!(pText.Trim() == String.Empty))
        {
            ret = pText;
        }
        return ret;
    }   //  end method
    //  Methode prüft, ob das Austrittsdatum länger als 12 Monate zurück liegt
    //  und setzt dem entsprechend das Flag 0 oder 1
    private static int checkAustritt(String pPer_austrittsdatum)
    {
        int ret = 1;    //  Default auf 1 gesetzt
        if(!(pPer_austrittsdatum.Trim() == String.Empty))
        {
            DateTime jetzt = System.DateTime.Now;
            DateTime austritt = DateTime.ParseExact(pPer_austrittsdatum, "ddMMyyyy", System.Globalization.CultureInfo.CurrentCulture);
            TimeSpan diff = jetzt.Subtract(austritt);
            if (diff.Days > 365)
            {
                ret = 0;
            }
        }
        return ret;
    }   //  end method
    //  Methode wandelt ein String Datum ddmmyyyy in ein DateTime um
    private static Object stringToDate(String pStringDate)
    {
        Object ret = DBNull.Value;
        try
        {
            if (!(pStringDate.Trim() == String.Empty))
            {
                ret = DateTime.ParseExact(pStringDate, "ddMMyyyy", System.Globalization.CultureInfo.CurrentCulture);
            }
        }
        catch (Exception ex)
        {
            ret = new DateTime(1800, 1, 1);
        }
        return ret;
    }   //  end method
};

It woul help us alot if someone can help us.

Raw pointer access to in-memory tables

$
0
0

Hello, I realize this is quite an odd question, but I was wondering if it's possible to obtain raw pointers to rows stored in an in-memory table introduced in SQL Server 2014.

What I am trying to do is to use AMD Kaveri APU in conjunction with SQL Server 2014. The APU has 500+ shader cores that can perform an operation on a piece of memory in parallel, and since SQL Server 2014 already keeps these tables in memory, I was hoping there is a way to reference these tables directly via pointers that can be used by APU cores (I could create wrapper code in CLR if needed) rather than taking data out of the database and creating in-memory arrays. All data types I am interested in are fixed length (doubles) and tables can be locked in the "read-only" state while read operations take place.

Is it possible to access in-memory tables via raw pointers?


 

Database not getting created on executing .sql file

$
0
0

Hi all. I have made some changes to a database model using model-first. After VS 2013 generates the sql file (which i expect to right click on and execute to get changes updated to my database), when i try to execute the file, i get errors such as:

Msg 3726, Level 16, State 1, Line 50
Could not drop object 'dbo.Users' because it is referenced by a FOREIGN KEY constraint.
Msg 3726, Level 16, State 1, Line 53
Could not drop object 'dbo.Answers' because it is referenced by a FOREIGN KEY constraint.
Msg 3726, Level 16, State 1, Line 56
Could not drop object 'dbo.Questions' because it is referenced by a FOREIGN KEY constraint.
Msg 2714, Level 16, State 6, Line 93
There is already an object named 'Users' in the database.
Msg 2714, Level 16, State 6, Line 101
There is already an object named 'Answers' in the database.
Msg 2714, Level 16, State 6, Line 109
There is already an object named 'Questions' in the database.
Msg 1779, Level 16, State 0, Line 153
Table 'Users' already has a primary key defined on it.
Msg 1750, Level 16, State 0, Line 153
Could not create constraint. See previous errors.
Msg 1779, Level 16, State 0, Line 159
Table 'Answers' already has a primary key defined on it.
Msg 1750, Level 16, State 0, Line 159
Could not create constraint. See previous errors.
Msg 1779, Level 16, State 0, Line 165
Table 'Questions' already has a primary key defined on it.
Msg 1750, Level 16, State 0, Line 165
Could not create constraint. See previous errors.
Msg 1769, Level 16, State 1, Line 215
Foreign key 'FK_SectionQuestion' references invalid column 'SectionSectionId' in referencing table 'Questions'.
Msg 1750, Level 16, State 0, Line 215
Could not create constraint. See previous errors.

Below is my generated .sql file:

-- --------------------------------------------------
-- Entity Designer DDL Script for SQL Server 2005, 2008, 2012 and Azure
-- --------------------------------------------------
-- Date Created: 08/06/2014 15:59:58
-- Generated from EDMX file: E:\My Documents\Visual Studio 2013\Projects\ExamGenerator\ExamGenerator\ExamDatabase.edmx
-- --------------------------------------------------

SET QUOTED_IDENTIFIER OFF;
GO
USE [master];
GO
IF SCHEMA_ID(N'dbo') IS NULL EXECUTE(N'CREATE SCHEMA [dbo]');
GO

-- --------------------------------------------------
-- Dropping existing FOREIGN KEY constraints
-- --------------------------------------------------

IF OBJECT_ID(N'[dbo].[FK_ExamSection]', 'F') IS NOT NULL
    ALTER TABLE [dbo].[Sections] DROP CONSTRAINT [FK_ExamSection];
GO
IF OBJECT_ID(N'[dbo].[FK_UserExam]', 'F') IS NOT NULL
    ALTER TABLE [dbo].[Exams] DROP CONSTRAINT [FK_UserExam];
GO
IF OBJECT_ID(N'[dbo].[FK_SectionQuestion]', 'F') IS NOT NULL
    ALTER TABLE [dbo].[Questions] DROP CONSTRAINT [FK_SectionQuestion];
GO
IF OBJECT_ID(N'[dbo].[FK_QuestionAnswer]', 'F') IS NOT NULL
    ALTER TABLE [dbo].[Answers] DROP CONSTRAINT [FK_QuestionAnswer];
GO
IF OBJECT_ID(N'[dbo].[FK_QuestionSubQuestion]', 'F') IS NOT NULL
    ALTER TABLE [dbo].[SubQuestions] DROP CONSTRAINT [FK_QuestionSubQuestion];
GO
IF OBJECT_ID(N'[dbo].[FK_SubQuestionSubQuestionsAnswer]', 'F') IS NOT NULL
    ALTER TABLE [dbo].[SubQuestionsAnswers] DROP CONSTRAINT [FK_SubQuestionSubQuestionsAnswer];
GO

-- --------------------------------------------------
-- Dropping existing tables
-- --------------------------------------------------

IF OBJECT_ID(N'[dbo].[Exams]', 'U') IS NOT NULL
    DROP TABLE [dbo].[Exams];
GO
IF OBJECT_ID(N'[dbo].[Sections]', 'U') IS NOT NULL
    DROP TABLE [dbo].[Sections];
GO
IF OBJECT_ID(N'[dbo].[Users]', 'U') IS NOT NULL
    DROP TABLE [dbo].[Users];
GO
IF OBJECT_ID(N'[dbo].[Answers]', 'U') IS NOT NULL
    DROP TABLE [dbo].[Answers];
GO
IF OBJECT_ID(N'[dbo].[Questions]', 'U') IS NOT NULL
    DROP TABLE [dbo].[Questions];
GO
IF OBJECT_ID(N'[dbo].[SubQuestions]', 'U') IS NOT NULL
    DROP TABLE [dbo].[SubQuestions];
GO
IF OBJECT_ID(N'[dbo].[SubQuestionsAnswers]', 'U') IS NOT NULL
    DROP TABLE [dbo].[SubQuestionsAnswers];
GO

-- --------------------------------------------------
-- Creating all tables
-- --------------------------------------------------

-- Creating table 'Exams'
CREATE TABLE [dbo].[Exams] (
    [ExamID] int IDENTITY(1,1) NOT NULL,
    [UnitCode] nvarchar(max)  NOT NULL,
    [UnitName] nvarchar(max)  NOT NULL,
    [ExamDate] nvarchar(max)  NULL,
    [Duration] float  NOT NULL,
    [Instructions] nvarchar(max)  NOT NULL,
    [University] nvarchar(max)  NOT NULL,
    [Course] nvarchar(max)  NOT NULL,
    [UserUserId] int  NOT NULL
);
GO

-- Creating table 'Sections'
CREATE TABLE [dbo].[Sections] (
    [SectionId] int IDENTITY(1,1) NOT NULL,
    [SectionName] nvarchar(max)  NOT NULL,
    [Marks] int  NOT NULL,
    [ExamExamID] int  NOT NULL
);
GO

-- Creating table 'Users'
CREATE TABLE [dbo].[Users] (
    [UserId] int IDENTITY(1,1) NOT NULL,
    [UserName] nvarchar(max)  NOT NULL,
    [Password] nvarchar(max)  NOT NULL
);
GO

-- Creating table 'Answers'
CREATE TABLE [dbo].[Answers] (
    [AnswerId] int  NOT NULL,
    [AnswerPhrase] nvarchar(max)  NULL,
    [Diagram] varbinary(max)  NULL
);
GO

-- Creating table 'Questions'
CREATE TABLE [dbo].[Questions] (
    [QuestionId] int IDENTITY(1,1) NOT NULL,
    [QuestionPhrase] nvarchar(max)  NOT NULL,
    [Diagram] varbinary(max)  NULL,
    [Marks] decimal(18,1)  NOT NULL,
    [SectionSectionId] int  NOT NULL
);
GO

-- Creating table 'SubQuestions'
CREATE TABLE [dbo].[SubQuestions] (
    [SubQuestionId] int IDENTITY(1,1) NOT NULL,
    [SubQuestionPhrase] nvarchar(max)  NULL,
    [Diagram] varbinary(max)  NULL,
    [Marks] decimal(18,0)  NULL,
    [QuestionQuestionId] int  NOT NULL
);
GO

-- Creating table 'SubQuestionsAnswers'
CREATE TABLE [dbo].[SubQuestionsAnswers] (
    [SubQuestionAnswerId] int  NOT NULL,
    [AnswerPhrase] nvarchar(max)  NULL,
    [Diagram] varbinary(max)  NULL
);
GO

-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------

-- Creating primary key on [ExamID] in table 'Exams'
ALTER TABLE [dbo].[Exams]
ADD CONSTRAINT [PK_Exams]
    PRIMARY KEY CLUSTERED ([ExamID] ASC);
GO

-- Creating primary key on [SectionId] in table 'Sections'
ALTER TABLE [dbo].[Sections]
ADD CONSTRAINT [PK_Sections]
    PRIMARY KEY CLUSTERED ([SectionId] ASC);
GO

-- Creating primary key on [UserId] in table 'Users'
ALTER TABLE [dbo].[Users]
ADD CONSTRAINT [PK_Users]
    PRIMARY KEY CLUSTERED ([UserId] ASC);
GO

-- Creating primary key on [AnswerId] in table 'Answers'
ALTER TABLE [dbo].[Answers]
ADD CONSTRAINT [PK_Answers]
    PRIMARY KEY CLUSTERED ([AnswerId] ASC);
GO

-- Creating primary key on [QuestionId] in table 'Questions'
ALTER TABLE [dbo].[Questions]
ADD CONSTRAINT [PK_Questions]
    PRIMARY KEY CLUSTERED ([QuestionId] ASC);
GO

-- Creating primary key on [SubQuestionId] in table 'SubQuestions'
ALTER TABLE [dbo].[SubQuestions]
ADD CONSTRAINT [PK_SubQuestions]
    PRIMARY KEY CLUSTERED ([SubQuestionId] ASC);
GO

-- Creating primary key on [SubQuestionAnswerId] in table 'SubQuestionsAnswers'
ALTER TABLE [dbo].[SubQuestionsAnswers]
ADD CONSTRAINT [PK_SubQuestionsAnswers]
    PRIMARY KEY CLUSTERED ([SubQuestionAnswerId] ASC);
GO

-- --------------------------------------------------
-- Creating all FOREIGN KEY constraints
-- --------------------------------------------------

-- Creating foreign key on [ExamExamID] in table 'Sections'
ALTER TABLE [dbo].[Sections]
ADD CONSTRAINT [FK_ExamSection]
    FOREIGN KEY ([ExamExamID])
    REFERENCES [dbo].[Exams]
        ([ExamID])
    ON DELETE NO ACTION ON UPDATE NO ACTION;

-- Creating non-clustered index for FOREIGN KEY 'FK_ExamSection'
CREATE INDEX [IX_FK_ExamSection]
ON [dbo].[Sections]
    ([ExamExamID]);
GO

-- Creating foreign key on [UserUserId] in table 'Exams'
ALTER TABLE [dbo].[Exams]
ADD CONSTRAINT [FK_UserExam]
    FOREIGN KEY ([UserUserId])
    REFERENCES [dbo].[Users]
        ([UserId])
    ON DELETE NO ACTION ON UPDATE NO ACTION;

-- Creating non-clustered index for FOREIGN KEY 'FK_UserExam'
CREATE INDEX [IX_FK_UserExam]
ON [dbo].[Exams]
    ([UserUserId]);
GO

-- Creating foreign key on [SectionSectionId] in table 'Questions'
ALTER TABLE [dbo].[Questions]
ADD CONSTRAINT [FK_SectionQuestion]
    FOREIGN KEY ([SectionSectionId])
    REFERENCES [dbo].[Sections]
        ([SectionId])
    ON DELETE NO ACTION ON UPDATE NO ACTION;

-- Creating non-clustered index for FOREIGN KEY 'FK_SectionQuestion'
CREATE INDEX [IX_FK_SectionQuestion]
ON [dbo].[Questions]
    ([SectionSectionId]);
GO

-- Creating foreign key on [AnswerId] in table 'Answers'
ALTER TABLE [dbo].[Answers]
ADD CONSTRAINT [FK_QuestionAnswer]
    FOREIGN KEY ([AnswerId])
    REFERENCES [dbo].[Questions]
        ([QuestionId])
    ON DELETE NO ACTION ON UPDATE NO ACTION;
GO

-- Creating foreign key on [QuestionQuestionId] in table 'SubQuestions'
ALTER TABLE [dbo].[SubQuestions]
ADD CONSTRAINT [FK_QuestionSubQuestion]
    FOREIGN KEY ([QuestionQuestionId])
    REFERENCES [dbo].[Questions]
        ([QuestionId])
    ON DELETE NO ACTION ON UPDATE NO ACTION;

-- Creating non-clustered index for FOREIGN KEY 'FK_QuestionSubQuestion'
CREATE INDEX [IX_FK_QuestionSubQuestion]
ON [dbo].[SubQuestions]
    ([QuestionQuestionId]);
GO

-- Creating foreign key on [SubQuestionAnswerId] in table 'SubQuestionsAnswers'
ALTER TABLE [dbo].[SubQuestionsAnswers]
ADD CONSTRAINT [FK_SubQuestionSubQuestionsAnswer]
    FOREIGN KEY ([SubQuestionAnswerId])
    REFERENCES [dbo].[SubQuestions]
        ([SubQuestionId])
    ON DELETE NO ACTION ON UPDATE NO ACTION;
GO

-- --------------------------------------------------
-- Script has ended
-- --------------------------------------------------

I was actually making changes to foreign keys on Table "Answer" and "SubAnswer" from Table "Question", and "SubQuestion" when i encountered this problem. I have even deleted the entire database, but still from VS i don't get a prompt of "missing database" or anything along those lines. Is it i making an error or is it Visual Studio that is confused?


There is never infinite resources.

After working for a while an SQLCLR assembly wont load

$
0
0

I have a user defined aggregate function in an assembly called Watchdog.
I use that function in a stored procedure.
All the sudden after running just fine for a day it throws an error as soon as I try to execute the stored procedure with this error:

Msg 10314, Level 16, State 12, Procedure spwdAutomaticAction, Line 70
An error occurred in the Microsoft .NET Framework while trying to load assembly id 65541. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error: 
System.IO.FileNotFoundException: Could not load file or assembly 'watchdog, Version=0.0.0.0, Culture=neutral, PublicKeyToken=fffbd94e193b6c65' or one of its dependencies. The system cannot find the file specified.
System.IO.FileNotFoundException: 
   at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
   at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   at System.Reflection.Assembly.Load(String assemblyString)

I have verified that the Watchdog assembly still has PERMISSION_SET = UNSAFE and that the only assembly it references also has it. Why would it say FileNotFoundException?

Call web service from CLR

$
0
0

Thanks all for suggestions, I have decided to write CLR SP to call web service. I have few question 

a)I am using SQL 2012 and VSTS 12 to write CLR SP  in Database project template. But I don't see any option to add web service reference.Could someone please help me on the same ?  

b) Does it make any difference if web service is Created on Java or dot net ?

Please suggest.


Gaur

how to solve : Conversion failed when converting date and/or time from character string

$
0
0

hi there

my query :

cmd = new SqlCommand("SELECT RTRIM(invoiceNo) as [Order No.],RTRIM(InvoiceDate) as [Order Date],RTRIM(SubTotal) as [SubTotal],RTRIM(VATPer) as [Vat+ST %],RTRIM(VATAmount) as [VAT+ST Amount],RTRIM(DiscountPer) as [Discount %],RTRIM(DiscountAmount) as [Discount Amount],RTRIM(GrandTotal) as [Grand Total],RTRIM(TotalPayment) as [Total Payment],RTRIM(PaymentDue) as [Payment Due] from Invoice_Info where InvoiceDate between @d1 and @d2 order by InvoiceDate desc", con);
               cmd.Parameters.Add("@d1", SqlDbType.DateTime, 30, "InvoiceDate").Value = dtpInvoiceDateFrom.Value.Date;
               cmd.Parameters.Add("@d2", SqlDbType.DateTime, 30, "InvoiceDate").Value = dtpInvoiceDateTo.Value.Date;

i use date timepicker / vs2010 / sql server 2008 r2 

tnx


Calling Unsafe ODBC commands from CLR C# Assembly

$
0
0

I will try to make this as clear and concise as possible. I have a C# CLR UDF that is calling an unsafe C DLL that makes ODBC calls.  Everything is working as expected, EXCEPT, that memory keeps slowly disappearing and after a few minutes the long SQL query calling the UDF ends with the error:

Msg 701, Level 17, State 130, Line 1
There is insufficient system memory in resource pool 'default' to run this query.

Can anyone see in the code below where memory might be slowly leaked? For example, is it ok to Bind the parameters and results one time at startup, or should I rebind them each time the statement is executed?

Here is the stripped down C code in the unsafe DLL. I have omitted all the error checking, but retcode is returning SQL_SUCCESS in all cases:

Called one time at startup:

SQLLEN		g_sqllen = SQL_NTS;
SQLHENV g_henv = NULL;
SQLHDBC h_hdbc = NULL;
SQLHSTMT h_stmt = NULL;
SQLRETURN   retcode;
char g_Param1[256], g_Param2[256];
char g_Result1[256], g_Result2[256], ...;
SQLLEN g_Result1Len = 0, g_Result2Len = 0, ...;
char g_MyQuery = "SELECT ..."; // will always result in a single row result set

retcode=SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &g_henv);
retcode=SQLSetEnvAttr(g_henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
retcode=SQLSetEnvAttr(g_henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_UINTEGER);
retcode=SQLAllocHandle(SQL_HANDLE_DBC, g_henv, &g_hdbc);
retcode=SQLDriverConnect(g_hdbc, 0, connString, SQL_NTS, ...);
retcode = SQLAllocHandle(SQL_HANDLE_STMT, g_hdbc, &g_hstmt);
retcode = SQLPrepare(context->hstmt, (SQLCHAR*)g_MyQuery, SQL_NTS);
retcode = SQLBindParameter(g_hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, sizeof(g_Param1), 0, g_Param1, 0, (SQLLEN*)&g_sqllen); 
retcode = SQLBindParameter(g_hstmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, sizeof(g_Param2), 0, g_Param2, 0, (SQLLEN*)&g_sqllen); 
retcode = SQLBindCol(g_hstmt, 1, SQL_C_CHAR, g_Result1, sizeof(g_Result1), &g_Result1Len);
retcode = SQLBindCol(g_hstmt, 2, SQL_C_CHAR, g_Result2, sizeof(g_Result2), &g_Result2Len);
...

Called repeatedly by the C# UDF:

.. populate g_Param1, g_Param2, ...
retcode = SQLExecute(g_hstmt);
retcode = SQLFetch(g_hstmt);
retcode = SQLCloseCursor(g_hstmt);

Finally, here is the code in the C# UDF that calls the unsafe DLL call

String Param1 = "...";
String Param2 = "...";
...
byte[] b_Result1 = new byte[256];
byte[] b_Result2 = new byte[256];
...
string s_Result1, s_Result2, ...;
Int retcode = UnsafeCall(
	Param1,
	Param2,
	b_Result1,
	b_Result2,
	...
	);
s_Result1 = Encoding.ASCII.GetString(b_Result1).TrimEnd('\0');
s_Result2 = Encoding.ASCII.GetString(b_Result2).TrimEnd('\0');
...

Thanks.

Neil
www.netlib.com



Failed to initialize the Common Language Runtime (CLR) v2.0.50727 with HRESULT 0x80131522. You need to restart SQL server to use CLR integration features

$
0
0
            

Hi,

ISSUE:

We are having an .NET application which uses database hosted in another server.

We are able to browse the .NET application. But when we try to search the contents in the application(fetching data from the database that is hosted in another server) we are getting the below error.

ERROR:

An error occurred in the application. Please contact your system administrator.

Description: Exception of type 'System.Web.HttpUnhandledException' was thrown.

Exception details: Failed to initialize the Common Language Runtime (CLR) v2.0.50727 with HRESULT 0x80131522. You need to restart SQL server to use CLR integration features.

Stack trace: at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.pages_search_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\6269c012\8546e139\App_Web_24ogqvca.3.cs:line 0 at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Steps Taken:

1)Restarted SQL services in the database server

2)Recycled the application pool and application

3)restarted IIS

4)Restarted the application server

5)Re-installed .NET 2.0 in the database server(according to Microsoft kb article 2003681)

6) Cleared files under the path c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary
ASP.NET Files\root\6269c012\8546e139 and restarted IIS

None of the above options helped us.

The database server has SQL server 2005:Microsoft SQL Server 2005 - 9.00.4060.00 (X64)   Mar 17 2011 13:06:52   Copyright (c) 1988-2005 Microsoft Corporation  Enterprise Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 2)

8 CPUs

and the CLR is enabled.

select * from assemblies

Output:

UserDefinedAggregates 1 65536 userdefinedaggregates, version=0.0.0.0, culture=neutral, publickeytoken=null, processorarchitecture=msil 1 SAFE_ACCESS 1 2007-10-23 11:10:38.597 2007-10-23 11:10:38.597

select * from sys.dm_clr_properties

OUTPUT:

directory 
version 
state CLR initialization permanently failed

When I right click and select Properties of the assembly I get a dialog box with the below message

"Failed to initialize the Common Language Runtime (CLR) v2.0.50727 with HRESULT 0x80131522. You need to restart SQL server to use CLR integration features(Microsoft SQL server,Error: 6512)"

please help me in solving this issue.

Thanks,

Priyadarshini Sathiyamoorthy

Application Read Data from .mdb Database file within visual Studio.But, fails when it runs under SQL Server as the Assembly

$
0
0
I have created an .Net Class Library for Reading and writing data from mdb file to SQL Server database. When i run it in Visual studio Application it works fine. but, When i created an assembly for the same in SQL Server the assmebly is unable to access the mdb file. The mdb file is located in remote system in the same network and SQL server is running as windows authentication. how to fix it. Any suggestions that makes it work . 

RehaanKhan. M

Problem with CLR Assemblies(Beginner)!!

$
0
0

Hi,

 

I'm trying to execute an sp which is calling a CLR assembly and on execution, i get the following error:

 

An error occurred in the Microsoft .NET Framework while trying to load assembly id 65537. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error:

System.IO.FileLoadException: Could not load file or assembly 'emailserviceclr, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An error relating to security occurred. (Exception from HRESULT: 0x8013150A)

System.IO.FileLoadException:

   at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)

   at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)

   at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)

   at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)

   at System.Reflection.Assembly.Load(String assemblyString)

 

Please let me know what can i do to fix this error as i'm using this CLR for the very first time.

 

Please guide me on this.

 

Thanks,

Deepti

Performance problem

$
0
0

Hi, I'm having a performance problem I cannot solve, so I'm hoping anyone here has some advice.

Our system consists of a central database server, and many applications (on various servers) that connect to this database.
Most of these applications are older, legacy applications.
They use a special mechanism for concurrency that was designed, also a long time ago.
This mechanism requires the applications to lock a specific table with a TABLOCKX before making any changes to the database (in any table).
This is of course quite nasty as it essentially turns the database into single user mode, but we are planning to phase this mechanism out.
However, there is too much legacy code to simply migrate everything right away, so for the time being we're stuck with it.

Secondly, this central database may not become too big because the legacy applications cannot cope with large amounts of data.
So, a 'cleaning' mechanism was implemented to move older data from the central database to a 'history' database.
This cleaning mechanism was created in newer technology; C# .NET.
It is actually a CLR stored procedure that is called from a SQL job that runs every night on the history server.
But, even though it is new technology, the CLR proc *must* use the same lock as the legacy applications because they all depend on the correct use of this lock.

The cleaning functionality is not a primary process, so it does not have high priority.
This means that any other application should be able to interrupt the cleaning and get handled by SQL first.
Therefore, we designed the cleaning so that it cleans as few data as possible per transaction, so that any other process can get the lock right after committing each cleaning transaction.
On the other hand, this means that we do have a LOT of small transactions, and because each transaction is distributed, they are expensive and so it takes a long time for the cleaning to complete.

Now, the problem: when we start the cleaning process, we notice that the CPU shoots up to 100%, and other applications are slowed down excessively.
It even caused one of our customer's factories to shut down!
So, I'm wondering why the legacy applications cannot interrupt the cleaning.
Every cleaning transaction takes about 0.6 seconds, which may seem long for a single transaction, but this also means any other application should be able to interrupt within 0,6 seconds.
This is obviously not the case; it seems the cleaning session 'steals' all of the CPU, or for some reason other SQL sessions are not handled anymore, or at least with serious delays.

I was thinking about one of the following approaches to solve this problem:
1) Add waits within the CLR procedure, after each transaction. This should lower the CPU, but I have no idea whether this will allow the other applications to interrupt sooner. (And I really don't want the factory to shut down twice!)
2) Try to look within SQL Server (using DMV's or something) and see whether I can determine why the cleaning session gets more CPU. But I don't know whether this information is available, and I have no experience with DMV's.

So, to round up:
- The total cleaning process may take a long time, as long as it can be interrupted ASAP.
- The cleaning statements themselves are already as simple as possible so I don't think more query tuning is possible.
- I don't think it's possible to tell SQL Server that specific SQL statements have low priority.

Can anyone offer some advice on how to handle this?

Regards,
Stefan

Viewing all 780 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>