Archiv der Kategorie: Datenbanken

Unter Datenbanken verstehe ich alle persistenten Speicherungssysteme die über ein relationales, objektorientiertes oder hierarchisches Datenmodell und über eine standardisierte Abfragesprache wie SQL, XQuery etc… verfügen.
Auch Datenbank-APIs wie Hibernate passen in diese Kategorie.

C#.NET + MS SQL Server : Nach INSERT direkt die Auto-Increment ID erhalten ohne zweite Abfrage

Problem

Um die Auto-Increment ID zu erhalten werden desöfteren 2 Statements abgesetzt, obwohl das INSERT-Statement direkt die Auto-Increment ID zurückgeben kann

Ansatz – Approach

Anstelle von comm.ExecuteNonQuery() sollte man lieber comm.ExecuteScalar() mit SELECT SCOPE_IDENTITY() kombinieren.

Lösung – Solution

public string insertMainTherapyData(string serial_no
                    ,string therapy_start
                    ,string machine_type
                    ,string file_source
                    ,string dialog_version
                    ,string tlc_version
                    ,string versions
                    ,DateTime uploaded_on
                    ,string uploaded_by
                    ,bool processed
                    ,string user_original_file
                    ,string user_country
                    ,string user_comment
                    ,string user_upload_reason
                    ,string user_location)
{
    string sqlStatement=@"
        INSERT INTO [dbo].[therapy]
                    ([serial_no]
                    ,[therapy_start]
                    ,[machine_type]
                    ,[file_source]
                    ,[dialog_version]
                    ,[tlc_version]
                    ,[versions]
                    ,[uploaded_on]
                    ,[uploaded_by]
                    ,[processed]
                    ,[user_original_file]
                    ,[user_country]
                    ,[user_comment]
                    ,[user_upload_reason]
                    ,[user_location])
        VALUES
                    (@serial_no
                    ,@therapy_start
                    ,@machine_type
                    ,@file_source
                    ,@dialog_version
                    ,@tlc_version
                    ,@versions
                    ,@uploaded_on
                    ,@uploaded_by
                    ,@processed
                    ,@user_original_file
                    ,@user_country
                    ,@user_comment
                    ,@user_upload_reason
                    ,@user_location);
            SELECT SCOPE_IDENTITY()
            ";
    int myID = -1;
    SqlConnection conn = new SqlConnection(MyConfigurationManager.prdSqlServerString);
    try
    {
        conn.Open();
        SqlCommand comm = new SqlCommand();
        comm.Connection = conn;
        comm.CommandText = sqlStatement;
        comm.Parameters.AddWithValue("serial_no", serial_no);
        comm.Parameters.AddWithValue("therapy_start", therapy_start);
        comm.Parameters.AddWithValue("machine_type", machine_type);
        comm.Parameters.AddWithValue("file_source", file_source);
        comm.Parameters.AddWithValue("dialog_version", dialog_version);
        comm.Parameters.AddWithValue("tlc_version", tlc_version);
        comm.Parameters.AddWithValue("versions", versions);
        comm.Parameters.AddWithValue("uploaded_on", uploaded_on);
        comm.Parameters.AddWithValue("uploaded_by", uploaded_by);
        comm.Parameters.AddWithValue("processed", processed);
        comm.Parameters.AddWithValue("user_original_file", user_original_file);
        comm.Parameters.AddWithValue("user_country", user_country);
        comm.Parameters.AddWithValue("user_comment", user_comment);
        comm.Parameters.AddWithValue("user_upload_reason", user_upload_reason);
        comm.Parameters.AddWithValue("user_location", user_location);
        myID = Convert.ToInt32(comm.ExecuteScalar());
    }
    catch (Exception ex)
    {
        return "ERROR: "+ex.Message;
    }
    finally
    {
        conn.Close();
    }

    return myID.ToString();
}

MS SQL Server: Last Index Of / lastIndexOf / Get last Index Of

Problem

There is no SQL Function to get the last index of a string.

Ansatz – Approach

The first two lines only declare a variable myString with content SER-SOP-12 to Test the combined SQL Functions.
The SELECT-Clause returns the lastIndex of (can be used in standard MS SQL Statements)

Lösung – Solution

Just copy it to the MS SQL Server Management Studio in a query window to test and press F5:

DECLARE @myString AS varchar(255)
SET @myString ='SER-SOP-12'
SELECT LEN(@myString )-CHARINDEX('-', REVERSE(@myString )) 

Get Microsoft Jet 4.0 Driver working on 64-Bit Windows Server

Problem

The Microsoft JET 4.0 Driver, which can open .MDB / Access Files, is only available for 32-Bit Systems

Ansatz – Approach

Register the DLLs for the operating system

Lösung – Solution

Solution 1 (Especially for IIS)

In IIS 7.x click on the app pool of your application -> advanced settings and look at the „General“ Section. The second Attribute is „Run in 32 Bit mode“. Check this.
Restart IIS.
If it is still not working, go on with Solution 2.

Im IIS Manager markiert man den AppPool der Anwendung und kann rechts auf „Advanced Settings“ (Erweiterte Einstellungen) klicken. Im „General“-Abschnitt (Allgemein) kann man im 2. Attribut sagen, man möchte im 32-Bit-Modus starten. Danach sollte der JET Treiber auch gehen.

Solution 2 (Especially for local applications)

The solution is to manually register those DLLs.

go to Start->Run and type cmd
this starts the Command Prompt
(also available from Start->Programs->Accessories->Command Prompt)

type cd .. and press return
type cd .. and press return again (keep doing this until the prompt shows :\> )

now you need to go to a special folder which might be c:\windows\system32 or it might be c:\winnt\system32 or it might be c:\windows\sysWOW64
try typing each of these eg
cd c:\windows\sysWOW64
(if it says The system cannot find the path specified, try the next one)
cd c:\windows\system32
cd c:\winnt\system32
when one of those doesn’t cause an error, stop, you’ve found the correct folder.

now you need to register the OLE DB 4.0 DLLs by typing these commands and pressing return after each

regsvr32 Msjetoledb40.dll
regsvr32 Msjet40.dll
regsvr32 Mswstr10.dll
regsvr32 Msjter40.dll
regsvr32 Msjint40.dll

Sparx Systems Enterprise Architect + SQL Queries : SQL Abfragen innerhalb von Enterprise Architect absetzen

Problem

Wer schon einmal versucht hat, eine lokale .EAP Datei in Microsoft Access zu öffnen, erlebt sein blaues Wunder, denn im Prinzip ist eine .EAP Datei nichts anderes als eine MS Access Datenbank (also ein .mdb-File), auf welches man SQL Queries absetzen kann. Bei der Migration eines lokalen .EAP Files in einen normalen SQL-Server, muss man zunächst die Datenstruktur anlegen und anschließend den Import starten. Eine großartige Transformation der Daten zwischen den Formaten findet also gar nicht statt. Was passiert aber wenn man kein MS Access / SQL Studio zur Verfügung hat?

Ansatz – Approach

Nutzung des kostenlosen Tools MDB Plus von Alex Nolan (das ist eine Windows Delphi Anwendung, die einfach gestartet werden kann).

Lösung – Solution

Das Tool lässt sich hier downloaden: http://www.alexnolan.net/ .
Anschließend geht man auf „Open“ und stellt die Datei-Extensionsuche von .mdb auf *.* um – danach kann man .eap Dateien öffnen.

Atlassian JIRA+MS SQL Server Get values from multiple version picker custom field in SQL / Mulitple Version Picker Werte über SQL Query erhalten

Problem

The version strings of custom field, that can select multiple versions, shall be selected

Approach – Ansatz

The table projectversion can be used to connect to CustomFieldValue.NUMBERVALUE

Solution – Lösung

SELECT pk.PROJECT_KEY+'-'+CAST(a.issuenum AS varchar(max)) as issue, pv.vname
FROM project_key pk
INNER JOIN jiraissue a ON pk.PROJECT_ID=a.PROJECT 
INNER JOIN CustomFieldValue b ON a.ID=b.ISSUE
INNER JOIN customfield c ON b.CUSTOMFIELD=c.id 
INNER JOIN projectversion pv ON pv.ID=b.NUMBERVALUE
WHERE c.CFName = 'LUA Version(s)' 
--AND pk.PROJECT_KEY+'-'+CAST(a.issuenum AS varchar(max)) ='NDS-4352'
ORDER BY 1

MS SQL Server: Stored Procedure mit Übergabeparameter

Problem

Es soll eine Stored Procedure erstellt werden

Ansatz – Approach

– Verwendung von SQL

Voraussetzung – Prerequirement

Create Procedure Permission/Berechtigung

Lösung – Solution

Dieser Code wird in ein SQL Management Studio Abfragefenter kopiert, markiert und mit F5 ausgeführt.

IF OBJECT_ID ( ‚dbo.sp_PreviousAcitivites‘, ‚P‘ ) IS NOT NULL
DROP PROCEDURE dbo.sp_PreviousAcitivites;
GO
CREATE PROCEDURE dbo.sp_PreviousAcitivites
@StartPoint nvarchar(50)
AS

SET NOCOUNT ON;
SELECT ‚>’+@StartPoint+‘<' GO [/javascript] Mehrere Übergabeparameter werden durch Kommas getrennt. Aufruf der Stored Procedure: [javascript] dbo.sp_PreviousAcitivites 'Bla' [/javascript]

MS SQL Server: Remove / Strip HTML Tags from Field – HTML Tags entfernen

Problem

Aus einer Selektion sollen alle HTML Tags entfernt werden.

Ansatz – Approach

– Erstellen einer Function
– SQL Abfrage absetzen (z.B. i.e. dbo.udf_StripHTML(‚HTML‚))

– Create a custom function
– Make your SQL Statement (i.e. dbo.udf_StripHTML(‚HTML‚))

Lösung – Solution

Als erstes wird die Funktion udf_StripHTML(STRING) erstellt:

CREATE FUNCTION [dbo].[udf_StripHTML] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX) AS
BEGIN
    DECLARE @Start INT
    DECLARE @End INT
    DECLARE @Length INT
    SET @Start = CHARINDEX('<',@HTMLText)
    SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
    SET @Length = (@End - @Start) + 1
    WHILE @Start > 0 AND @End > 0 AND @Length > 0
    BEGIN
        SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
        SET @Start = CHARINDEX('<',@HTMLText)
        SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
        SET @Length = (@End - @Start) + 1
    END
    RETURN LTRIM(RTRIM(@HTMLText))
END
&#91;/javascript&#93;
Der obige Text wird hierzu einfach in das SQL Server Management Studio kopiert, markiert und ausgeführt. 

Zum Schluss wird die Abfrage abgesetzt:
&#91;javascript&#93;
SELECT dbo.udf_StripHTML(htmlTextFeld) FROM Tabelle

-- ODER

SELECT dbo.udf_StripHTML('<a href="irrsinn.php">Grober Unfug</a> ist keine <b>Methode</b> sondern <div style="font-family:Times;">Kriegsführung</div>')

Microsoft SQL Server Express: Wie man die Datenbankgröße herausfindet / How-to get the Database size

Prämisse

Bei MS SQL Server 2012 Express und 2014 Express darf die maximale Datenbankgröße nur 10 GB betragen.

Problem

Wie findet man die Datenbankgröße heraus?

Ansatz

SQL Server Server Statement

Lösung – Solution

SELECT 
      database_name = DB_NAME(database_id)
    , log_size_mb = CAST(SUM(CASE WHEN type_desc = 'LOG' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = 'ROWS' THEN size END) * 8. / 1024 AS DECIMAL(8,2))
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))
FROM sys.master_files WITH(NOWAIT)
WHERE database_id = DB_ID() -- for current db 
GROUP BY database_id

Microsoft SQL Server: Enable SQL Server Autentication (mixed mode) / Login für SQL User mit Connectionstring ermöglichen

Problem

Der SQL Server erlaubt keine Zugriffe über einen Connectionstring.
Microsoft SQL Server does not allow

Analyse

Also Standardauthentifizierungsmethode ist „Windows Authentication“ ausgewählt. Man benötigt „SQL Authentication„, was als „mixed mode“ im Microsoft SQL Server Kontext genannt wird.

Vorgehensweise

1.) Öffnen Sie Microsoft SQL Server Management Studio Express und klicken Sie mit der rechten Maustaste auf den Server Knoten.

schritt1

2.) Im Navigationsmenü auf der linken Seite wählen Sie den Punkt „Security“ aus und sehen die folgenden Einstellungen, in denen Sie „mixed mode“ aktivieren können, um Zugriffe per Connectionstring grundsätzlich zu erlauben.

schritt2

MS SQL Server: The database principal owns a schema in the database, and cannot be dropped

Problem

Ein Microsoft SQL Server User kann nicht gelöscht werden. Es erscheint die Fehlermeldung

„The database principal owns a schema in the database, and cannot be dropped“

Ansatz – Approach

Nutzung des Systemkatalogs zum finden der betroffenen Schemas
Änderung der Berechtigungen mit ALTER AUTHORIZATION
Löschen des Benutzers

Lösung – Solution

SELECT name FROM sys.schemas WHERE principal_id = USER_ID('benutzer')

Gefundene Principals (z.B. db_owner…) in Alter Authorization eintragen:

ALTER AUTHORIZATION ON SCHEMA::db_owner TO dbo
ALTER AUTHORIZATION ON SCHEMA::db_datareader TO dbo

DROP USER benutzer