SQL Server Stored Procedure to generate different types of reference number

At work, there is a website that we need to generate several types of unique reference numbers. Numbers such as A000013579 for answer id and Q000024680 for question id. To generate numbers like that, we created a stored procedure. I can see that we can use this method in other websites as well.

First, we created a table to save the last used number. Let’s call it [SequenceTable]. In this table, we need 4 columns: [Type],[Prefix],[LastNumber] and [Length].
values for [Type] column could be: “Answer ID”
values for [Prefix] column could be: “A”
values for [LastNumber] column could be: 13579
values for [Length] column could be: 10

Then, we created a Stored Procedure that take value for [Type]. Look for the value of [LastNumber] where [Type] is the input. Fill 0’s using the REPLICATE function. Increase the value of [LastNumber] by 1 and update it in the table. Append prefix and return it as an output. The stored procedure is defined as follow:


ALTER PROCEDURE [dbo].[sp_GetNextReferenceID]
  @Type as varchar(25),
  @ID varchar(20) OUTPUT
  @Prefix VARCHAR(10),
  @LastNumber int, 
  @Length smallint,
  @charLastNumber as varchar(15)
  if exists (Select * From SEQUENCETABLE Where Type = @Type)
      Select @prefix = Prefix,
          @LastNumber = LastNumber,
          @Length = Length
      From SEQUENCETABLE Where Type = @Type
      Select @LastNumber = @LastNumber + 1
      Update SEQUENCETABLE Set LastNumber = @LastNumber Where Type = @Type

      -- To Fill 0 in between with the REPLICATE function
      Select @charLastNumber = REPLICATE('0',@length - len(@LastNumber) - len(@prefix)) 
+ cast(@LastNumber as varchar(10))
      Select @ID = @prefix + @charLastNumber
	RAISERROR('Invalid Type',16,1)

use coalesce function to concat field values

Problem: I got 3 tables: [Posts],[Tags] and [PostsTags]
When the tables join, I got multiple records for each post with distinct tags.
I want a table that contains single record for each post with tags concatenated.


  1. In SQL Server 2005, I created a Scalar-valued Function that takes one parameter (the post id). This function returns concatenated values of the tag name given the post id.
  2. Then I called this function in the Views and Stored Procedure.
  3. The Scalar-valued Function is defined as below:

ALTER FUNCTION [dbo].[SVF_TagNameByPostID] (@post_id int)
RETURNS nvarchar(1000)
	DECLARE @Result nvarchar(1000)

	SELECT @Result = COALESCE(@Result + '|', '') +
	CAST(Table_Tags.tag_name AS nvarchar(50))
	Table_PostsTags ON Table_Tags.tag_id = Table_PostsTags.tag_id INNER JOIN
	View_Posts ON Table_PostsTags.post_id = View_Posts.post_id
	WHERE View_Posts.post_id = @post_id

	RETURN @Result

DataBinder.Eval function

I am creating a blog and I need to preserve white space for user comment. So I need to put <pre> tag around the comment content. In ASP.NET, I could do it in the ItemDataBound function and then use the FindControl function and append <pre> tags to the text property of the label. But there is a much better and easier way. Use the DataBinder.Eval function like below

<asp:Label ID=”CommentLabel” runat=”server” Text='<%# DataBinder.Eval(Container.DataItem,”comment_content”,”<pre>{0}</pre>”) %>’></asp:Label>

In my case, the “comment_content” is the name of the field in my table that contains the user htmlencoded content.

Using CSS Friendly Control Adapter to existing project

What it is: http://aspnet.4guysfromrolla.com/articles/112906-1.aspx
Download and Install: http://www.codeplex.com/cssfriendly

1. Downloading the current release. Go to the Releases tab. You should see three prominent links to files. The zip file contains the source code, the CSSFriendly.dll file contains the compiled source code, and the the CSSFriendlyAdapters.browser file is a configuration file. You only need the dll and browser files.
2. Add a reference to CSSFriendly.dll. This is typically done by right-clicking your web project, choosing the Add References command, browsing for the CSSFriendly.dll file, and clicking OK.
3. Add the CSSFriendlyAdapters.browser file to the AppBrowsers folder in the root of your web project. If the AppBrowsers folder doesn’t exist, create it.

You may notice the autoFormat you selected for your gridview or other controls is not working anymore. You will have to use the cssclass property of the control to specify the style you want.

Escape double quote in C#

If you want to represent a double quote in a string literal, the escape sequence is two double quotes with “@” system in the front.

string myString = @”<xml attribute=“”my attribute“”/>”;

move sql server 2005 database to sql server 2000

I need to move a database that I created in sql server 2005 express to an old development environment which run sql server 2000. After searching on the web for half hour, I follow the instructions in one of the posts. It works. Below are the steps to do this.

How to Downgrade a Database from SQL Server 2005 to SQL Server 2000

Step 1 Generating Scripts for the Database Elements and Structures

1) Right-click over the desired Database at 2005, Choose Tasks and the Generate Scripts (Option).

2) At the pop-up Dialog Box click at the Script All Objects in the selected Databases check box, to activate it and then Click the Next Button.

3) Set the following Elements to the following Values

a. Script Collation , set to TRUE

b. Script Database Create, set to TRUE

c. Script of SQL Version, set to SQL SERVER 2000

d. Script foreign keys, set to FALSE

e. Script Triggers, set to FALSE

Then Hit the Next button

4) Select the way the generated scripts should be saved (There are different selections. The most common one is Clipboard). Finally click the Next button till you reach the end.

5) Click Finish

After completing this procedure, we have to move to the SQL SERVER 2000 environment. Here, by using the Query Analyzer, we will have to run the scripts that were generated using the master database. Copy and Paste the script at the Query Analyzer and run it. After that the Structure of the Database will be created.

Be careful, the SQL Server 2005 Edition inserts the Views in a random place through the script. Therefore, all the scripts that are referred to the Views MUST be moved to the end of the script. If the Query Analyzer shows some errors do not be bothered. Delete all the elements created from the script and after you fix the code run it again.

Step2 Moving the data from 2005 to 2000

1) After completing the previous step successfully, moving the data follows. Right-click at the 2005 database you used to run the previous step and select Tasks and then choose the Export Data (option).

2) From the pop-up Dialog Box, select the Source Db and Click at the Next Button.

3) At the next step you will have to choose the destination server and the destination Database for the Data to be exported. Then Click Next.

4) A List of all the Source Database’s Elements will appear in the screen. Select one by one all the Elements you wish to move and for each one click at the button Edit Mappings (Located at the bottom right corner of the Dialog Box just under the Elements list). A new Dialog box will pop-up. Select the Delete rows in Destination Tables option and activate the Enable Identity Insert Option. (Remember to repeat this action for each of the selected Element from the list that will be moved.

CAUTION!!! A malfunction of the SQL Server 2005 has been found. Not sure why, after multiple tries I have observed that when I tried to move more than twelve Elements at once, the Export Data Wizard of SQL Server 2005 seemed to disable the Enable Identity Insert Option that was activated over the Edit Mappings Dialog Box. But if the number of the selected Elements is smaller than 12 no problem seemed to appear.

Step 3 Generating Scripts for the Database Foreign Keys and Triggers

Finally, to successfully finish the downgrade of the Database, the Triggers and the Foreign Keys of the DB must be produced. The procedure that should be followed is the one stated next:

1) Right-Click at the SQL 2005 Database and Select from Tasks Menu the Generate Scripts Option.

2) Using the pop-up Dialog Box make sure that the check box Script All Objects in the selected Databases is not enabled and hit the Next Button.

3) Set all the Elements on the List to a False Value except the ones that follow:

a. Include IF NOT EXISTS , set to TRUE

b. Script Owner, set to TRUE

c. Script of SQL Version, set to SQL SERVER 2000

d. Script foreign keys, set to TRUE

e. Script Triggers, set to TRUE

Then Hit the Next button

4) After finishing reading the Elements of the Database, a new list will appear at the Dialog Box. Make sure that you select ONLY THE TABLES of the Database and hit the Next Button.

5) At the screen that follows hit the Select All button and the Next.

6) Select the way the generated scripts should be saved (There are different selections. The most common one is Clipboard). Finally click the Next button till you reach the end.

7) Click Finish Button.

After completing this procedure, we have to move to the SQL SERVER 2000 environment. Here, by using the Query Analyzer, we will have to run the scripts that were generated using the master database. Copy and Paste the script at the Query Analyzer and run it. After that the Foreign Keys and the Triggers of the Database will be created.

After these steps the database should be fully functional under the SQL Server 2000 edition.

Other Thoughts:
The keyword in the store procedures needs to be changed. For example, the transaction keywords is different in version 2005 from version 2000.


Ways to pass data for asp.net website

  1. ViewState – Maintain data for postback for a page
  2. Context items collection – Simple data pass from 1 page to another. (common use for server farm)
  3. QueryString – put value in the URL
  4. Session – Server store value per user (example: user id)
  5. Application – For the whole web application
  6. Cache – Server storing data among all users (example: the product table)
  7. Cookie – Store information on the user’s pc for a long time (example: track first time visit)
  8. PreviousPage object

…and others

Wilco Syntax Highlighter for ASP.NET Tutorial

I am looking for a good syntax highlighter for my new site. I was searching the forum on ASP.NET and eventually stumble upon Wilco’s syntax highlighter. It is open source which gives you the power to configure it. That site lacks a good tutorial and no examples are provided, so it took me a while to figure out how to customized it. (maybe because I’m still a newbie)

First, open and build Wilco’s project in Visual Studio. Then go to “Wilco.SyntaxHighlighting\bin\Debug” folder to get copy the compiled dll file and paste into the bin folder of your other project. Add reference and browse the dll file. Add it to the toolbox by right clicking the area in the toolbox section, browse the dll file again. You should see 4 more controls in the toolbox. Now just drag and drop it into your web page. Select the mode, language and text.

To customize the look, you can change the style setting in the SyntaxHighlighterTemplates.cs file.

Context.Items vs. ViewState

To pass values from one page to another, Context.Items and ViewState are used most often.

It is important to keep in mind that values stored in the Context.Items collection only last for the current request. If I were to do a postback on the page, the Context item would be lost. Most of the time this is convienient since we only need to store that value between pages and no longer.

To keep track of values between postback, use ViewState. Unlike Context.Items collection that is used to transfer data from one page to another, ViewState can be only used for the same page. It is useful for postback. Also, Context.Items is used very often in the server farm architecture.

It’s common to use this in the page_load function of the page. Check out the example below. Note that the IsPostBack condition below. If that is not there, then the postback of the page will read Context.Items(“id”) again which will be null. This will cause a problem. That is why it is important to have it there.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ProductToShow As Integer
If Not Me.IsPostBack Then
ProductToShow = Context.Items("Id")
Me.ViewState("Id") = ProductToShow
ProductToShow = Me.ViewState.Item("Id")
End If
End Sub

Putting corners using a single image with CSS

  1. The corner image (26 x 26 pixels)
  2. In the CSS file, it only display 13 x 13 pixels of the background image. The background-position property chooses which portion to be displayed.:

    .box .tl, .box .tr, .box .bl, .box .br
    {background-image:url(Images/corners.gif); background-repeat:no-repeat; width:13px; height:13px}
    .tl {background-position: left top}
    .tr {background-position: right top}
    .bl {background-position: left bottom}
    .br {background-position: right bottom}

  3. In the web page:

    <table cellpadding=”0″ cellspacing=”0″ class=”box”>
    td class=”tl”></td>
    td class=”t”></td>
    td class=”tr”></td>
    td class=”l”></td>
    td class=”c”>
    asp:ContentPlaceHolder ID=”ContentPlaceHolder1″ runat=”server” />
    td class=”r”></td>
    td class=”bl”></td>
    td class=”b”></td>
    td class=”br”></td>

Other thought:
I should have used <div> instead of <td>…Now I know more.