Navigation

Search

Categories

On this page

Creating Dynamic Charts
How to Automate Database Backups with SQL Server Express
SQL REPLACE Function In UPDATE Statement
Basic Transactions in SQL Server 2008
Basic Error Handling in SQL Server 2008
SQL Server – Scalar Function With Parameter
SQL Server - Debugging with variables and output parameters

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 245
This Year: 51
This Month: 0
This Week: 0
Comments: 0

Sign In
Pick a theme:

# Friday, April 30, 2010
Friday, April 30, 2010 6:42:11 PM (GMT Daylight Time, UTC+01:00) ( Charts )

 

I’ve been working on creating custom data-driven charts for use in a new product.  We looked at several options including Microsoft’s free Chart Controls but ultimately decided to go with Dundas Chart because of their excellent customer service and support.  Their product makes it relatively easy to create nice looking charts for ASP.NET pages such as this pie chart.

'Chart - Total Annual Compensation
    Sub Bind_Chart_TotalAnnualComp()
    
        Dim strCEOBaseSalary As Double
        Dim strCEOBonus As Double
        Dim strCEONonEqIncentComp As Double
        Dim strCEOPensionNQDC As Double
        Dim strCEOAllOtherCompensation As Double
        
        'Create a connection
        Dim myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("TearSheet_ConnString").ConnectionString)

        'Create the command object, passing in the SQL string
        Const strSQL As String = "p_Chart_TotalAnnualComp"
        Dim myCommand As New SqlCommand(strSQL)
        myCommand.CommandType = CommandType.StoredProcedure
        myCommand.Parameters.AddWithValue("@id_company", lblid_company.Text)
                                  
        'Set the datagrid's datasource to the datareader and databind
        myConnection.Open()
        myCommand.Connection = myConnection
        Dim myReader As SqlDataReader = myCommand.ExecuteReader()
        
        Dim xValues As String() = {"Salary", "Bonus", "Non-Equity Incentive Comp", "Pension/NQDC Earnings", "All Other Compensation"}
        Dim yValues As New List(Of Double)
        With myReader
            If .HasRows Then
                While .Read
                    yValues.Add(Double.Parse(.GetValue(0)))
                    strCEOBaseSalary = Double.Parse(.GetValue(0))
                    yValues.Add(Double.Parse(.GetValue(1)))
                    strCEOBonus = Double.Parse(.GetValue(1))
                    yValues.Add(Double.Parse(.GetValue(2)))
                    strCEONonEqIncentComp = Double.Parse(.GetValue(2))
                    yValues.Add(Double.Parse(.GetValue(3)))
                    strCEOPensionNQDC = Double.Parse(.GetValue(3))
                    yValues.Add(Double.Parse(.GetValue(4)))
                    strCEOAllOtherCompensation = Double.Parse(.GetValue(4))
                End While
            End If
        End With
        
        Chart_TotalAnnualComp.Series("Default").Points.DataBindXY(xValues, yValues.ToArray())
        
        myConnection.Close()
        myConnection.Dispose()
        
        'Make the chart 3D
        Chart_TotalAnnualComp.ChartAreas("Default").Area3DStyle.Enable3D = True
        
        'Don't let the text in the legend wrap
        Chart_TotalAnnualComp.Legends("Default").TextWrapThreshold = 0
        
        'Chart Title
        Chart_TotalAnnualComp.Legends("Default").Title = "Total Annual Compensation"
              
        'Add the series and values for each
        Chart_TotalAnnualComp.Series(0).Points(0).LegendText = "Salary " & FormatCurrency(strCEOBaseSalary.ToString(), 0)
        Chart_TotalAnnualComp.Series(0).Points(1).LegendText = "Bonus " & FormatCurrency(strCEOBonus.ToString(), 0)
        Chart_TotalAnnualComp.Series(0).Points(2).LegendText = "Non-Equity Incentive Comp " & FormatCurrency(strCEONonEqIncentComp.ToString(), 0)
        Chart_TotalAnnualComp.Series(0).Points(3).LegendText = "Pension/NQDC Earnings " & FormatCurrency(strCEOPensionNQDC.ToString(), 0)
        Chart_TotalAnnualComp.Series(0).Points(4).LegendText = "All Other Compensation " & FormatCurrency(strCEOAllOtherCompensation.ToString(), 0)
        
        'Add custom tooltips showing each series value
        Chart_TotalAnnualComp.Series(0).Points(0).ToolTip = "Salary " & FormatCurrency(strCEOBaseSalary.ToString(), 0)
        Chart_TotalAnnualComp.Series(0).Points(1).ToolTip = "Bonus " & FormatCurrency(strCEOBonus.ToString(), 0)
        Chart_TotalAnnualComp.Series(0).Points(2).ToolTip = "Non-Equity Incentive Comp " & FormatCurrency(strCEONonEqIncentComp.ToString(), 0)
        Chart_TotalAnnualComp.Series(0).Points(3).ToolTip = "Pension/NQDC Earnings " & FormatCurrency(strCEOPensionNQDC.ToString(), 0)
        Chart_TotalAnnualComp.Series(0).Points(4).ToolTip = "All Other Compensation " & FormatCurrency(strCEOAllOtherCompensation.ToString(), 0)
        
        'This prevents the values from showing up inside the pie chart
        Chart_TotalAnnualComp.Series(0)("PieLabelStyle") = "Disabled"
    End Sub
Comments [0] | | # 
# Sunday, April 25, 2010
Sunday, April 25, 2010 2:08:14 PM (GMT Daylight Time, UTC+01:00) ( SQL )
# Friday, April 16, 2010
Friday, April 16, 2010 8:49:00 PM (GMT Daylight Time, UTC+01:00) ( SQL )


REPLACE searches the the first string for any occurance of the the second string and replaces it with the third string.

SELECT Replace('Clarence Thomas is a crazy fool!', 'crazy', 'old')

gives us

Clarence Thomas is a old fool!

Here is how to use REPLACE in conjunction with an UPDATE statement.

UPDATE dbo.authors
SET    city = REPLACE(city, 'Salt', 'Olympic')
WHERE  city LIKE 'Salt%';
Comments [0] | | # 
# Tuesday, April 13, 2010
Tuesday, April 13, 2010 3:40:18 PM (GMT Daylight Time, UTC+01:00) ( SQL )


Here are some simple examples on how to Begin, Commit and Rollback transactions in SQL Server 2008.

-- *********************
-- Explicit Transactions
-- *********************

-- Use @@TRANCOUNT
USE Northwind;
GO

BEGIN TRANSACTION;
UPDATE dbo.Employees
    SET LastName = 'Da Volio'
WHERE LastName = 'Davolio';

IF @@TRANCOUNT > 0
    BEGIN
        PRINT N'The transaction is active.';
        ROLLBACK TRANSACTION;
        PRINT N'The transaction has been rolled back.';
    END
GO

SELECT LastName FROM dbo.Employees;

-- Use @@ERROR 

SELECT message_id, text from sys.messages;

-- Simple error handling
DECLARE @err int
BEGIN TRANSACTION;
INSERT INTO dbo.Customers (CustomerID, CompanyName)
    VALUES ('ALFKI', 'New ALFKI');
SET @Err = @@ERROR
IF @Err = 0
    BEGIN
        PRINT 'Commit transaction.';
        COMMIT
    END
ELSE
    BEGIN    
        PRINT 'Error = ' + CAST(@Err AS varchar(10));
        ROLLBACK
    END
GO
Comments [0] | | # 
Tuesday, April 13, 2010 3:31:18 PM (GMT Daylight Time, UTC+01:00) ( SQL )


Here are some examples on how to use Try/Catch and RaiseError to address error handling in SQL Server 2008

-- ************************
-- TRY/CATCH Error Handling
-- ************************

BEGIN TRY
    BEGIN TRANSACTION;
    INSERT INTO dbo.Customers (CustomerID, CompanyName)
        VALUES ('ALFKI', 'New ALFKI');
    COMMIT TRANSACTION;
    PRINT 'Transaction committed.';
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION;
    PRINT 'Transaction rolled back.';
END CATCH
GO

-- Display detailed error information
BEGIN TRY
    BEGIN TRANSACTION;
    INSERT INTO dbo.Customers (CustomerID, CompanyName)
        VALUES ('ALFKI', 'New ALFKI');
    COMMIT TRANSACTION;
    PRINT 'Transaction committed.';
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION;
    SELECT
        ERROR_NUMBER() AS Number,
        ERROR_SEVERITY() AS Severity,
        ERROR_STATE() AS State,
        ERROR_PROCEDURE() AS procedureName,
        ERROR_LINE() AS Line,
        ERROR_MESSAGE() AS messageText;
    PRINT 'Transaction rolled back.';
END CATCH
GO

-- Use RAISERROR in a TRY/CATCH
BEGIN TRY
    RAISERROR ('Error severity 9', 9, 1);
    RAISERROR ('Error severity 16', 16, 1);
END TRY

BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;

    SELECT 
        @ErrorMessage = ('In CATCH block: ' + ERROR_MESSAGE()),
        @ErrorSeverity = ERROR_SEVERITY();
    RAISERROR (@ErrorMessage, @ErrorSeverity, 1);
END CATCH;
GO

-- Create a stored procedure using TRY/CATCH and RAISERROR
CREATE PROCEDURE dbo.InsertCategoryTryCatch
    @CategoryName nvarchar(15) = NULL,
    @CategoryID int = NULL OUTPUT,
    @ReturnCode int = NULL OUTPUT,
    @ReturnMessage nvarchar(255) = NULL OUTPUT 
AS
    SET NOCOUNT ON

    BEGIN TRY
        -- Test if CategoryName null.
        IF @CategoryName IS NULL
            RAISERROR ('Validation failed: Null CategoryName.', 16, 1);

        -- Test if CategoryName already exists.
        IF EXISTS (SELECT CategoryName FROM dbo.Categories 
                WHERE CategoryName=@CategoryName)
            RAISERROR ('Validation failed: Duplicate CategoryName.', 16, 1);

        -- Begin the transaction.
        BEGIN TRANSACTION
        INSERT INTO dbo.Categories (CategoryName)
            VALUES (@CategoryName);
        COMMIT TRANSACTION;
        SET @CategoryID=SCOPE_IDENTITY();
        SELECT @ReturnCode=0, 
            @ReturnMessage='Success! ' + @CategoryName + ' added.';
    END TRY

    BEGIN CATCH
        -- Test to see if we're in a transaction.
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;

        -- Return error information to client.
        SELECT @ReturnCode = ERROR_NUMBER();
        SELECT @ReturnMessage = ERROR_MESSAGE() +
            ' Severity=' + CAST(ERROR_SEVERITY() AS nvarchar(2)) + 
            '; State=' + CAST(ERROR_STATE() AS nvarchar(2)) + 
            '; Proc=' + CAST(ERROR_PROCEDURE() AS nvarchar(50)) + 
            '; Line=' + CAST(ERROR_LINE() AS nvarchar(10));
    END CATCH
GO
Comments [0] | | # 
# Monday, April 05, 2010
Monday, April 05, 2010 12:54:54 AM (GMT Daylight Time, UTC+01:00) ( SQL )
-- Scalar function with parameter
CREATE FUNCTION dbo.fnProductsSoldByProduct
    (@ProductID int = null) 
    RETURNS int
    WITH RETURNS NULL ON NULL INPUT
AS
    BEGIN
        DECLARE @total int;
        SELECT @Total = SUM(Quantity)
            FROM dbo.[Order Details]
        WHERE ProductID = @ProductID;
        
        RETURN @Total;
    END
GO

Examples of how to call the function above
SELECT dbo.fnProductsSoldByProduct(NULL);
SELECT dbo.fnProductsSoldByProduct(DEFAULT);
SELECT dbo.fnProductsSoldByProduct(3);

-- Causes an error:
SELECT dbo.fnProductsSoldByProduct();
GO
--Another example
-- Create a scalar function to calculate a discount
CREATE FUNCTION dbo.fnCalcDiscountPrice 
(
    @price money,
    @discount int
)
RETURNS money
WITH RETURNS NULL ON NULL INPUT
AS
    BEGIN
        DECLARE @work money
        SELECT @work = @price - (@price * (@discount * .01))
        RETURN @work
    END;


-- Execute the function against the Products table
SELECT ProductID, ProductName, UnitPrice, 
    dbo.fnCalcDiscountPrice(UnitPrice,5) AS [5% Off],
    dbo.fnCalcDiscountPrice(UnitPrice,3) AS [3% Off]
FROM dbo.Products
ORDER BY UnitPrice DESC;
 
Comments [0] | | # 
# Sunday, April 04, 2010
Sunday, April 04, 2010 9:56:40 PM (GMT Daylight Time, UTC+01:00) ( SQL )


Here is a nice example of how to use output parameters in a stored procedure to debug the proc.

CREATE PROC dbo.InsertShipperOutputParams
    @CompanyName nvarchar(40) = NULL,
    @Phone nvarchar(24) = NULL,
    @ShipperID int = NULL OUTPUT,
    @ReturnCode int OUTPUT,
    @ReturnMessage varchar(255) OUTPUT
AS
    SET NOCOUNT ON;
    SET @ReturnCode = 0;
    SET @ReturnMessage = '';

    IF @CompanyName IS NULL
        SET @ReturnMessage = 'ShipperID is null.';
    ELSE
        BEGIN
            DECLARE @id int, @rows int, @error int;
            INSERT INTO dbo.Shippers(CompanyName, Phone)
                VALUES (@CompanyName, @Phone);
            SELECT @error = @@ERROR, @rows = @@ROWCOUNT, 
                @id = SCOPE_IDENTITY();
            IF @error = 0 AND @rows > 0
                BEGIN
                    SET @ShipperID = @id;
                    SET @ReturnCode = @rows;
                    SET @ReturnMessage = 'Success!';
                END
            ELSE
                SET @ReturnMessage = 'Error=' 
                    + ISNULL(@error, 'No number for this error.');
        END
GO
Comments [0] | | #