European Windows 2019 Hosting BLOG

BLOG about Windows 2019 Hosting and SQL 2019 Hosting - Dedicated to European Windows Hosting Customer

European SQL Server 2022 Hosting :: SQL Server CLR Integration and SSIS Automation with C#

clock April 25, 2025 09:45 by author Peter

Developers frequently encounter the difficulty of fusing intricate database operations and data transportation pipelines with application logic in contemporary enterprise systems. This gap can be successfully closed with the aid of two potent features from the Microsoft SQL Server ecosystem.

  • SQL Server CLR Integration: Leverage .NET capabilities within SQL Server for advanced procedural logic.
  • SSIS Automation in C#: Programmatically control and automate ETL pipelines using SQL Server Integration Services (SSIS).

This article explores both concepts in depth, providing code examples, use cases, and best practices.

SQL CLR Functions in .NET: Embedding Business Logic in SQL Server

SQL CLR (Common Language Runtime) integration allows developers to create stored procedures, functions, aggregates, and triggers using any .NET language (like C#). This is particularly useful when T-SQL falls short for tasks requiring procedural logic, complex math, string operations, or external library support.

Example: A Simple CLR Scalar Function in C#
[SqlFunction]
public static int AddNumbers(int a, int b)
{
    return a + b;
}

After compiling this function into a DLL and registering it with SQL Server, it can be invoked just like a built-in T-SQL function.
SELECT dbo.AddNumbers(100, 250); -- Returns 350

Step-by-Step Deployment Process
Enable CLR in SQL Server

sp_configure 'clr enabled', 1;
RECONFIGURE;


Compile the C# code into a Class Library (DLL)
Use Visual Studio to create a Class Library project.
Set the project to target .NET Framework, not .NET Core.

Deploy the Assembly to SQL Server.
CREATE ASSEMBLY MyClrAssembly
FROM 'C:\Path\To\MyClrAssembly.dll'
WITH PERMISSION_SET = SAFE;


Create the Function.
CREATE FUNCTION dbo.AddNumbers(@a INT, @b INT)
RETURNS INT
AS EXTERNAL NAME MyClrAssembly.[YourNamespace.YourClass].AddNumbers;

When to Use SQL CLR Functions?

Use Case Why Use CLR
Complex mathematical operations .NET has richer math libraries
String and regex manipulation .NET handles regex far better than T-SQL
File system or external access Use with EXTERNAL_ACCESS permission
Code reusability Centralize shared logic across apps & DB

Note. Use CLR sparingly for security and performance. Avoid overusing it for tasks that T-SQL handles well.

Automating ETL with SSIS from C#: Taking Control of Data Pipelines
SQL Server Integration Services (SSIS) is a widely used tool for ETL (Extract, Transform, Load) processes. While it’s typically run via SQL Agent jobs or the SSIS catalog, sometimes you need tighter control — dynamic execution, real-time monitoring, or conditional branching based on application logic.

Example: Running a Package from C#

using Microsoft.SqlServer.Dts.Runtime;

Application app = new Application();
Package package = app.LoadPackage(@"C:\Packages\MyPackage.dtsx", null);
DTSExecResult result = package.Execute();

if (result == DTSExecResult.Success)
{
    Console.WriteLine("Package executed successfully.");
}
else
{
    Console.WriteLine("Package execution failed.");
}

What You Can Automate with This?

  • Trigger SSIS packages based on real-time events (like user actions, webhooks, or workflows).
  • Dynamically select packages, connections, or parameters based on app logic.
  • Integrate with logging and monitoring systems for auditing ETL runs.
  • Schedule or queue package runs without using SQL Agent.

Requirements & Tips

Requirement Details
SSIS Runtime Ensure Microsoft.SqlServer.ManagedDTS is referenced.
Permissions App/service needs rights to run SSIS and access packages.
DTSX Package Availability Ensure the package path is correct and accessible.
SQL Server Data Tools (SSDT) For creating and debugging SSIS packages.

You can also manipulate variables, log events, and receive task-level execution results via the SSIS object model in C#.

Combining CLR + SSIS for End-to-End Automation
By using both CLR integration and SSIS automation in your application stack, you unlock powerful data and logic orchestration capabilities.

Practical Scenario
Imagine a financial reporting system.

  • You use SQL CLR functions to calculate custom interest models in queries.
  • You automate SSIS to pull raw transaction data nightly and load into your analytics warehouse.
  • Your C# application coordinates both — triggering ETL, monitoring outcomes, and presenting results in dashboards.

Security and Best Practices

  • Avoid UNSAFE permissions unless absolutely necessary for SQL CLR.
  • Use strong-named assemblies for CLR to prevent version conflicts and security risks.
  • Secure your package execution by using Windows authentication or proxy credentials in SSIS.
  • Isolate configuration: Read SSIS parameters from external configuration files or variables, not hardcoded paths.

Summary: Why This Matters

Feature Benefits
SQL CLR Integration Reuse .NET logic, enhance SQL performance, simplify complex operations
SSIS Automation in C# Real-time control over ETL, seamless integration with business logic

These technologies help you create agile, intelligent, and integrated data systems — essential in today’s data-driven applications.

Final Thoughts
SQL Server isn't just a database — it’s a platform for building smart, automated systems that react and scale with your application. Using CLR integration and SSIS automation, developers can tightly couple database processing with business workflows, reduce manual effort, and deliver greater value through code.

Ready to modernize your data workflows? Combine your C# skills with the power of SQL Server for next-level automation.

Full Class Example

using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Dts.Runtime;

namespace SqlServerIntegration
{
    public class SqlServerIntegrationHelper
    {
        /// <summary>
        /// SQL CLR function to add two numbers.
        /// Can be registered in SQL Server as a UDF.
        /// </summary>
        [SqlFunction]
        public static SqlInt32 AddNumbers(SqlInt32 a, SqlInt32 b)
        {
            return a + b;
        }

        /// <summary>
        /// Executes an SSIS package from a given .dtsx file path.
        /// Returns true if successful, false otherwise.
        /// </summary>
        /// <param name="packagePath">Full path to the .dtsx package file</param>
        /// <returns>True if successful, false if failed</returns>
        public static bool ExecuteSSISPackage(string packagePath)
        {
            try
            {
                Application app = new Application();
                Package package = app.LoadPackage(packagePath, null);

                DTSExecResult result = package.Execute();

                if (result == DTSExecResult.Success)
                {
                    Console.WriteLine("✅ SSIS Package executed successfully.");
                    return true;
                }
                else
                {
                    Console.WriteLine("❌ SSIS Package execution failed.");
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"⚠️ Error executing SSIS Package: {ex.Message}");
                return false;
            }
        }

        // Optional: Main method for standalone testing (Console App only)
        public static void Main()
        {
            Console.WriteLine("Running SSIS Package...");
            string path = @"C:\Packages\MyPackage.dtsx"; // Change this to your actual path
            ExecuteSSISPackage(path);
        }
    }
}

HostForLIFEASP.NET SQL Server 2022 Hosting

 



European SQL Server 2022 Hosting :: Schedule SSIS Jobs Step by Step with Screenshots

clock April 23, 2025 10:27 by author Peter

Follow the below steps.
Step 1. First, deploy the SSIS Package under Integration Services Catalogs.
Step 2. Expand SQL Server Agent option -> Jobs -> Create New Job
Step 3.  Once click on New Job below window will open:

 

Step 4. In the General tab - Enter your Job Name.
Step 5. In the Step tab - Click on the New button.

 

Step 6. Once you click on the New button -> below window will open.

  • Add Step name
  • Select Type as SQL Server Integration Package

In Package Option:

  • Select Server
  • Select the Package that you want to Schedule.

Now Select Configuration Option:
Check Parameters


Check Connection managers - Sometimes, you need to add a password if it's not autofill.
In the Advanced option - Select 32-bit runtime.


Then click OK. Now your step is created.

Step 7. Now click on the left Schedules option -> Click New Button -> Below window will open:


HostForLIFEASP.NET SQL Server 2022 Hosting

 



European SQL Server 2022 Hosting :: In SQL Server Databases, Dynamically Create Foreign Keys

clock April 14, 2025 10:30 by author Peter

Suppose you have just defined the primary keys in your database, but later on you want to use the foreign keys as well. In that scenario, defining the foreign keys in each table using the main key for the entire database is extremely challenging. This may be accomplished dynamically by writing a straightforward script that can read every table in the database, look for a field, and then, if the field is found in the database table, establish a foreign key. Attached is the script for the same.

This is the script for creating the Foreign Keys for all dependent tables:

Create a temp table to hold all user tables
IF OBJECT_ID('tempdb..#AllTables') IS NOT NULL DROP TABLE #AllTables;

-- Select all user-defined tables into a temporary table
SELECT name AS TableName
INTO #AllTables
FROM sys.tables
WHERE is_ms_shipped = 0;

-- Declare variables and cursor
DECLARE @TableName NVARCHAR(255);
DECLARE @SQL NVARCHAR(MAX);

DECLARE TableCursor CURSOR FOR
SELECT TableName FROM #AllTables;

-- Open cursor and iterate through each table
OPEN TableCursor;
FETCH NEXT FROM TableCursor INTO @TableName;

WHILE @@FETCH_STATUS = 0
BEGIN
    -- Check if 'CompanyID' column exists and no foreign key is defined (excluding 'CompanyMaster')
    IF EXISTS (
        SELECT 1
        FROM sys.columns
        WHERE object_id = OBJECT_ID(@TableName)
        AND name = 'CompanyID'
    ) AND NOT EXISTS (
        SELECT 1
        FROM sys.foreign_key_columns fkc
        JOIN sys.columns c
            ON fkc.parent_column_id = c.column_id
           AND fkc.parent_object_id = c.object_id
        WHERE c.name = 'CompanyID'
        AND fkc.parent_object_id = OBJECT_ID(@TableName)
        AND @TableName <> 'CompanyMaster'
    )
    BEGIN
        -- Build and execute SQL to add a foreign key constraint
        SET @SQL = '
        ALTER TABLE [' + @TableName + ']
        ADD CONSTRAINT FK_' + @TableName + '_CompanyID
        FOREIGN KEY (CompanyID) REFERENCES Company(CompanyID);';

        EXEC sp_executesql @SQL;
    END

    FETCH NEXT FROM TableCursor INTO @TableName;
END

-- Clean up
CLOSE TableCursor;
DEALLOCATE TableCursor;
DROP TABLE #AllTables;


After running this script, the Foreign Keys are created. To check this.

HostForLIFEASP.NET SQL Server 2022 Hosting



European SQL Server 2022 Hosting :: Understanding Conversion Functions in SQL

clock April 8, 2025 10:52 by author Peter

Conversion functions in SQL are used to change the data type of a value. These functions are essential when handling different data formats and ensuring consistency in data processing.

Types of Conversion Functions

  • CAST(): Converts an expression from one data type to another.
  • CONVERT(): Similar to CAST but allows formatting for date and numeric conversions.
  • TRY_CAST(): Similar to CAST but returns NULL instead of an error if conversion fails.
  • TRY_CONVERT(): Functions like CONVERT but returns NULL if conversion fails.
  • FORMAT(): Converts values into a formatted string.

Example Usage of Conversion Functions

1. Using CAST() Function
SELECT CAST(123.45 AS INT) AS ConvertedValue;

2. Using CONVERT() Function
SELECT CONVERT(VARCHAR, GETDATE(), 103) AS FormattedDate;

3. Using TRY_CAST() Function
SELECT TRY_CAST('123ABC' AS INT) AS Result;

Output. NULL (Fails due to non-numeric characters)


4. Using TRY_CONVERT() Function

SELECT TRY_CONVERT(INT, '456XYZ') AS Result;

Output. NULL (Fails due to non-numeric characters)

5. Using FORMAT() Function
SELECT FORMAT(1234567.89, 'N2') AS FormattedNumber;


Output. 1,234,567.89

Advantages of Conversion Functions

  • Helps standardize data representation across databases.
  • Allows formatting of numeric and date values.
  • Prevents errors when handling mixed data types.

HostForLIFEASP.NET SQL Server 2022 Hosting

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in