Showing posts with label MS SQL. Show all posts
Showing posts with label MS SQL. Show all posts

Saturday, October 8, 2011

Webhosting: Free webhosting for ASP.NET

Believe it or not, it is possible to host your ASP.NET application for free. Storage, bandwidth, etc. is of course limited, but it is a good offer for students and test applications.

Below we have listed different hosts that offer free ASP.NET hosting:
  1. Free ASP Web Hosting (2 GB storage, 20 GB bandwidth, includes MS SQL)
  2. Web Host for ASP.net (150 MB storage)
  3. Somee (150 MB storage, 5 GB transfer)
  4. AspHost4Free (100 MB storage, unlimited bandwidth)
  5. Free domain site (1 GB storage, unlimited bandwidth)
  6. 7 Host (50 MB storage)
  7. ASP Spider
  8. Brinkster (30 MB storage, 2 TB bandwidth) 
  9. HelioHost (using Mono Project on Linux servers)
You can also get free SSL certificates for your webserver:

MS SQL: Custom Date and Time functions

Transact-SQL really lack a the neccessary support for creating and modifying dates and times. Now and then I have the need for creating custom dates based on year, month and day. This is not an easy task. To simplify the manipulation of dates and times a small toolkit of userdefined functions has been developed:


Date and Time functions

Calendar functions

MS SQL: Create DateTime

To create a full DateTime structure in Transact-SQL we need to use two of our earlier defined userdefined functions.
 
 First we generate a raw base date, and then we add the hours, minutes and seconds.
 

-- Returns a dateTime value for the date and time specified.
create function [dbo].[sudf_Common_DateTime]
(
      @intYear    int,
      @intMonth   int,
      @intDay     int,
      @intHour    int,
      @intMinute  int,
      @intSecond  int
)
returns datetime
as
begin
      -- Create the datetime structure
      return dbo.sudf_Common_Time(@intHour, @intMinute,@intSecond, dbo.sudf_Common_Date(@intYear, @intMonth, @intDay))
end

MS SQL: Create Time

To create a new DateTime value for a given date and a given time, we can use the userdefined function below. We start by retrieving the raw date (no time portion) of the base date, and then add the hours, minutes and seconds.

-- Returns a datetime value for the specified time at the "base" date (1/1/1900)
CREATE function [dbo].[sudf_Common_Time]
(
      @intHour    int,
      @intMinute  int,
      @intSecond  int,
      @dtBaseDate datetime
)
returns datetime
as
begin
      -- Build the time
    return  dbo.sudf_Common_DateOnly(@dtBaseDate) +
                  dateadd(ss,(@intHour*3600) + (@intMinute*60) + @intSecond,0)
end

MS SQL: Date portion from DateTime

To return only the date portion of a DateTime variable, you need to use a combination of the dateadd and datediff functions in Transact-SQL.

-- Returns @DateTime at midnight; i.e., it removes the time portion of a DateTime value.
CREATE  function [dbo].[sudf_Common_DateOnly]
(
@dtDateTime DateTime
)
returns datetime
as
begin
      -- Get the date only
    return dateadd(dd, 0, datediff(dd, 0, @dtDateTime))
end

MS SQL: Create Date

There is no straight forward function in Transact-SQL to create a simple date based on year, month and day. Below we have created a userdefined function to handle this. Notice that the base date in Microsoft SQL Server is January 1st 1900. We generate the date by adding the year, month and day to the base date.

CREATE function [dbo].[sudf_Common_Date]
(
      @intYear int,
      @intMonth int,
      @intDay int
)
-- returns a datetime value for the specified year, month and day
returns datetime
as
begin
      -- Returns a date later than the base date (1.1.1900)
    return dateadd(month,((@intYear-1900)*12)+@intMonth-1,@intDay-1)
end

MS SQL: Time portion from DateTime

To get only the Time portion of a DateTime variable in Transact-SQL, you can use the following function:

-- Returns only the time portion of a DateTime, at the "base" date (1/1/1900)
CREATE function [dbo].[sudf_Common_TimeOnly]
(
      @dtDateTime datetime
)
returns datetime
as
begin
      -- Get the time only
    return dateadd(day, -datediff(day, 0, @dtDateTime), @dtDateTime)
end

Please notice that the base date is January 1st 1900. Any dates/times prior to this day won't work,

MS SQL: Constants

Transact-SQL does not offer a good way to support constants in your stored procedures or userdefined functions. This means that you either can choose to hardcode your constants or, the more elegant way, define a userdefined function for each "constant" value. To ensure optimal performance, the schemabinding keyword should be used.

Here is an example:

CREATE FUNCTION [dbo].[sudf_Security_Privilege_User]
(
)
RETURNS INT
with schemabinding
AS
BEGIN

      -- Return the access level
      RETURN (1);

END

In your stored procedure you can call the function the normal way, i.e.
set x = dbo.sudf_Security_Privilege_User();

MS SQL: MD5 Hash

The non-reversable hashing algorithm MD5 is supported in Microsoft SQL Server, but is not directly accessable though a simple transact-SQL function. Normally you would store the MD5 hash value as a hexadecimal string in your database. The HashBytes function returns a binary array of hash data. To convert the binary data to hex we need to use the function fn_varbintohexstr.


To make your code easier to read, I've made a wrapper in a custom userdefined function:

CREATE FUNCTION [dbo].[sudf_Common_Md5Hash]
(
      -- Add the parameters for the function here
      @strValue nvarchar(max)
)
RETURNS nvarchar(32)
AS
BEGIN
      -- Declare the return variable here
      declare @strResult nvarchar(32)

      -- Generate the MD5
      set @strResult = SubString(master.dbo.fn_varbintohexstr(HashBytes('MD5', @strValue)), 3, 32)
     
      -- Return the result of the function
      RETURN @strResult
END

MS SQL: Url Encode

There is no built-in function in Microsoft SQL Server to to support URL encoding. If you want to generate URLs with arguments on the fly in stored procedures, you would have to do the URL encoding yourself. URL encoding can be implemented in several ways. Either you can create your own custom userdefined function in MS SQL or create a custom library in .NET. The library can then be called from a stored procedure.

Here I will show how you can encode your URLs using a userdefined function:


CREATE FUNCTION [dbo].[audf_Common_UrlEncode](@strUrl varchar(max))
returns varchar(max)
AS
 begin
    -- Declare variables
    declare @intCount int,
            @strChar char(1),
            @i int,
            @strUrlReturn varchar(max)

    -- Initialize variables
    set @intCount       = Len(@strUrl);
    set @i              = 1;
    set @strUrlReturn   = '';  

    -- Loop through all characters
    while (@i <= @intCount)
    begin
        -- Get the character
        set @strChar = substring(@strUrl, @i, 1)

        -- Is ASCII character?
        if @strChar LIKE '[A-Za-z0-9()''*-._! ]'
         begin
            -- Just append character
            set @strUrlReturn = @strUrlReturn + @strChar
         end
        else
         begin
            -- Encode and append character
            set @strUrlReturn =
                   @strUrlReturn +
                   '%' +
                   SUBSTRING(sys.fn_varbintohexstr(CAST(@strChar as varbinary(max))),3,2)
         end
        -- Next character
        set @i = @i +1
     end

    -- Return the encoded URL
    return @strUrlReturn
 end

Friday, October 7, 2011

MS SQL: Atomic Insert or Update (UPSERT)

It is not straight forward to create an atomic insert or update statement in SQL Server, i.e. we update the row if it exists. Otherwise we insert a new row.

The following statement (notice the locks) will create a more or less atomic statement:


-- Start transaction
begin tran


-- Row Exists?
if not exists (select * from <table> with (updlock, rowlock, holdlock) where <PK = ...>    
begin
        <insert>
end
else
begin
        <update>
end

-- End Transaction
commit