Monday, February 25, 2013

Date and Time Functions (Transact-SQL)

The Transact-SQL date and time data types are listed in the following table.
Data type Format Range Accuracy Storage size (bytes) User-defined fractional second precision Time zone offset
time hh:mm:ss[.nnnnnnn] 00:00:00.0000000 through 23:59:59.9999999 100 nanoseconds 3 to 5 Yes No
date YYYY-MM-DD 0001-01-01 through 9999-12-31 1 day 3 No No
smalldatetime YYYY-MM-DD hh:mm:ss 1900-01-01 through 2079-06-06 1 minute 4 No No
datetime YYYY-MM-DD hh:mm:ss[.nnn] 1753-01-01 through 9999-12-31 0.00333 second 8 No No
datetime2 YYYY-MM-DD hh:mm:ss[.nnnnnnn] 0001-01-01 00:00:00.0000000 through 9999-12-31 23:59:59.9999999 100 nanoseconds 6 to 8 Yes No
datetimeoffset YYYY-MM-DD hh:mm:ss[.nnnnnnn] [+|-]hh:mm 0001-01-01 00:00:00.0000000 through 9999-12-31 23:59:59.9999999 (in UTC) 100 nanoseconds 8 to 10 Yes Yes
The Transact-SQL rowversion data type is not a date or time data type. timestamp is a deprecated synonym for rowversion.
The Transact-SQL date and time functions are listed in the following tables. For more information about determinism, see Deterministic and Nondeterministic Functions.

Functions That Get System Date and Time Values

All system date and time values are derived from the operating system of the computer on which the instance of SQL Server is running.

Higher-Precision System Date and Time Functions

SQL Server 2008 R2 obtains the date and time values by using the GetSystemTimeAsFileTime() Windows API. The accuracy depends on the computer hardware and version of Windows on which the instance of SQL Server is running. The precision of this API is fixed at 100 nanoseconds. The accuracy can be determined by using the GetSystemTimeAdjustment() Windows API.
Function Syntax Return value Return data type Determinism
SYSDATETIME SYSDATETIME () Returns a datetime2(7) value that contains the date and time of the computer on which the instance of SQL Server is running. The time zone offset is not included. datetime2(7) Nondeterministic
SYSDATETIMEOFFSET SYSDATETIMEOFFSET ( ) Returns a datetimeoffset(7) value that contains the date and time of the computer on which the instance of SQL Server is running. The time zone offset is included. datetimeoffset(7) Nondeterministic
SYSUTCDATETIME SYSUTCDATETIME ( ) Returns a datetime2(7) value that contains the date and time of the computer on which the instance of SQL Server is running. The date and time is returned as UTC time (Coordinated Universal Time). datetime2(7) Nondeterministic

Lower-Precision System Date and Time Functions

Function Syntax Return value Return data type Determinism
CURRENT_TIMESTAMP CURRENT_TIMESTAMP Returns a datetime2(7) value that contains the date and time of the computer on which the instance of SQL Server is running. The time zone offset is not included. datetime Nondeterministic
GETDATE GETDATE ( ) Returns a datetime2(7) value that contains the date and time of the computer on which the instance of SQL Server is running. The time zone offset is not included. datetime Nondeterministic
GETUTCDATE GETUTCDATE ( ) Returns a datetime2(7) value that contains the date and time of the computer on which the instance of SQL Server is running. The date and time is returned as UTC time (Coordinated Universal Time). datetime Nondeterministic

Functions That Get Date and Time Parts

Function Syntax Return value Return data type Determinism
DATENAME DATENAME ( datepart , date ) Returns a character string that represents the specified datepart of the specified date. nvarchar Nondeterministic
DATEPART DATEPART ( datepart , date ) Returns an integer that represents the specified datepart of the specified date. int Nondeterministic
DAY DAY ( date ) Returns an integer that represents the day day part of the specified date. int Deterministic
MONTH MONTH ( date ) Returns an integer that represents the month part of a specified date. int Deterministic
YEAR YEAR ( date ) Returns an integer that represents the year part of a specified date. int Deterministic

Functions That Get Date and Time Difference

Function Syntax Return value Return data type Determinism
DATEDIFF DATEDIFF ( datepart , startdate , enddate ) Returns the number of date or time datepart boundaries that are crossed between two specified dates. int Deterministic

Functions That Modify Date and Time Values

Function Syntax Return value Return data type Determinism
DATEADD DATEADD (datepart , number , date ) Returns a new datetime value by adding an interval to the specified datepart of the specified date. The data type of the date argument Deterministic
SWITCHOFFSET SWITCHOFFSET (DATETIMEOFFSET , time_zone) SWITCHOFFSET changes the time zone offset of a DATETIMEOFFSET value and preserves the UTC value. datetimeoffset with the fractional precision of the DATETIMEOFFSET Deterministic
TODATETIMEOFFSET TODATETIMEOFFSET (expression , time_zone) TODATETIMEOFFSET transforms a datetime2 value into a datetimeoffset value. The datetime2 value is interpreted in local time for the specified time_zone. datetimeoffset with the fractional precision of the datetime argument Deterministic

Functions That Set or Get Session Format

Function Syntax Return value Return data type Determinism
@@DATEFIRST @@DATEFIRST Returns the current value, for the session, of SET DATEFIRST. tinyint Nondeterministic
SET DATEFIRST SET DATEFIRST { number | @number_var } Sets the first day of the week to a number from 1 through 7. Not applicable Not applicable
SET DATEFORMAT SET DATEFORMAT { format | @format_var } Sets the order of the dateparts (month/day/year) for entering datetime or smalldatetime data. Not applicable Not applicable
@@LANGUAGE @@LANGUAGE Returns the name of the language that is currently being used. @@LANGUAGE is not a date or time function. However, the language setting can affect the output of date functions. Not applicable Not applicable
SET LANGUAGE SET LANGUAGE { [ N ] 'language' | @language_var } Sets the language environment for the session and system messages. SET LANGUAGE is not a date or time function. However, the language setting affects the output of date functions. Not applicable Not applicable
sp_helplanguage sp_helplanguage [ [ @language = ] 'language' ] Returns information about date formats of all supported languages. sp_helplanguage is not a date or time stored procedure. However, the language setting affects the output of date functions. Not applicable Not applicable

Functions That Validate Date and Time Values

Function Syntax Return value Return data type Determinism
ISDATE ISDATE ( expression ) Determines whether a datetime or smalldatetime input expression is a valid date or time value. int ISDATE is deterministic only if you use it with the CONVERT function, when the CONVERT style parameter is specified, and when style is not equal to 0, 100, 9, or 109.
Topic Description
Using Date and Time Data Provides information and examples that are common to date and time data types and functions.
CAST and CONVERT (Transact-SQL) Provides information about the conversion of date and time values to and from string literals and other date and time formats.
Writing International Transact-SQL Statements Provides guidelines for portability of databases and database applications that use Transact-SQL statements from one language to another, or that support multiple languages.
ODBC Scalar Functions (Transact-SQL) Provides information about ODBC scalar functions that can be used in Transact-SQL statements. This includes ODBC date and time functions.
Data Type Mapping with Distributed Queries Provides information about how date and time data types affect distributed queries between servers that have different versions of SQL Server or different providers.

Commonly Used Functions in SQL Server 2005/2008

  • DateTime Function in SQL Server
    • GETDATE()
    • DATEPART()
    • DATEDIFF()
    • DATENAME()
    • DAY()
    • MONTH()
    • YEAR()
  • String Functions  
    • ASCII()
    • CHAR()
    • NCHAR()
    • DIFFERENCE()  
    • LEFT()  
    • RIGHT()  
    • LTRIM()  
    • RTRIM()
    • REPLACE()
    • QUOTNAME()
    • REVERSE()   
    • CHARINDEX()
    • PATINDEX()
    • LEN()
    • STUFF()
    • SUBSTRING()
    • LOWER/UPPER()






DateTime Function in SQL Server

Below are the most commonly used DateTime function in SQL Server.
  • GETDATE()
  • DATEADD()
  • DATEPART()
  • DATEDIFF()
  • DATENAME()
  • DAY()
  • MONTH()
  • YEAR()

GETDATE()

GETDATE() is very common used method which returns exact date time from the system. It does not accept any parameter. Just call it like simple function.
Example :

Declare @Date datetime 
set @Date = (SELECT GETDATE());
Print @Date 
OutPut:

Aug 15 2009  9:04PM 

DATEADD()

DATEADD() is used to add or subtract datetime. Its return a new datetime based on the added or subtracted interval.
General Syntax

 DATEADD(datepart, number, date)
datepart is the parameter that specifies on which part of the date to return a new value. Number parameter is used to increment datepart.
Example :

Declare @Date datetime 
set @Date = (SELECT GETDATE());
print  @Date -- Print Current Date
-- Adding 5 days with Current Date
SELECT DATEADD(day, 5,@Date ) AS NewTime
Output :

Aug 15 2009  9:19PM
NewTime
-----------------------
2009-08-20 21:19:15.170

DATEPART()

DATEPART() is used when we need a part of date or time from a datetime variable. We can use DATEPART() method only with select command.
Syntax

DATEPART(datepart, date)
Example :

-- Get Only Year
SELECT DATEPART(year, GETDATE()) AS 'Year'
-- Get Only Month
SELECT DATEPART(month, GETDATE()) AS 'Month'
-- Get Only hour
SELECT DATEPART(hour, GETDATE()) AS 'Hour
Output :

Year
-----------
2009
Month
-----------
8
Hour
-----------
21

DATEDIFF()

DATEDIFF() is very common function to find out the difference between two DateTime elements.
Syntax

DATEDIFF(datepart, startdate, enddate)
Example :

-- Declare Two DateTime Variable
Declare @Date1 datetime 
Declare @Date2 datetime 
-- Set @Date1 with Current Date
set @Date1 = (SELECT GETDATE());
-- Set @Date2 with 5 days more than @Date1
set @Date2 = (SELECT DATEADD(day, 5,@Date1 ))
-- Get The Date Difference
SELECT DATEDIFF(day, @Date1, @Date2) AS DifferenceOfDay
Output :

DifferenceOfDay
---------------
5 

DATENAME()

DATENAME() is very common and most useful function to find out the date name from the datetime value.
Example

-- Get Today 
SELECT DATENAME(dw, getdate()) AS 'Today Is'
-- Get Mont name
SELECT DATENAME(month, getdate()) AS 'Month'
Output :

Today Is
------------------------------
Saturday
Month
------------------------------
August

DAY()

DAY() is used to get the day from any date time object.
Example:

SELECT DAY(getdate()) AS 'DAY'
Output :

DAY
-----------
15

MONTH()


SELECT MONTH(getdate()) AS 'Month'
Output :

Month
-----------
8

YEAR()


SELECT YEAR(getdate()) AS 'Year'
Output :

Year
-----------
2009

String Functions

Some of the String Functions comes very handy at times. Let us discuss them one by one.

ASCII()

Returns the ASCII code value of the leftmost character of a character expression.
Syntax

ASCII ( character_expression ) 

Arguments: character_expression : Is an expression of the type char or varchar.
Return Types: Int 
Example:

SELECT ASCII('A')  

SET TEXTSIZE 0
SET NOCOUNT ON
-- Create the variables for the current character string position 
-- and for the character string.
DECLARE @position int, @string char(15)
-- Initialize the variables.
SET @position = 1
SET @string = 'The codeProject'
WHILE @position <= DATALENGTH(@string)
   BEGIN
   SELECT ASCII(SUBSTRING(@string, @position, 1)),
      CHAR(ASCII(SUBSTRING(@string, @position, 1)))
    SET @position = @position + 1
   END
SET NOCOUNT OFF
Output:

-----------
65
----------- ----
84          T
----------- ----
104         h
----------- ----
101         e
----------- ----
and so on..... 
CHAR()  Converts an int ASCII code to a character.
Syntax  
CHAR ( integer_expression ) 
Arguments: integer_expression: Is an integer from 0 through 255. NULL is returned if the integer expression is not in this range.
Return Types:  character 
Example:
SET TEXTSIZE 0
SET NOCOUNT ON
DECLARE @intCounter int
SET @intCounter = 0

WHILE (@intCounter<= 255)
	BEGIN
		SELECT 'CHAR - ' + CHAR(@intCounter) + '. ASCII - ' + CONVERT(VARCHAR,@intCounter) 
		SET @intCounter = @intCounter + 1
	END


SET NOCOUNT OFF
Output:
CHAR - !. ASCII - 33
------------------------------------------------
CHAR - ". ASCII - 34
------------------------------------------------
CHAR - #. ASCII - 35
------------------------------------------------
CHAR - $. ASCII - 36
------------------------------------------------
CHAR - %. ASCII - 37
------------------------------------------------
CHAR - &. ASCII - 38
------------------------------------------------
CHAR - '. ASCII - 39
------------------------------------------------
CHAR - (. ASCII - 40
------------------------------------------------

and so on.....   

NCHAR() 

Return a unicode character representing a number passed as a parameter.
Syntax 
NCHAR ( integer_expression )  
Return Types:  character 
Example : 
SELECT NCHAR(97) 
OutPut
This will return the leter "a"

DIFFERENCE()

Returns an integer value that indicates the difference between the SOUNDEX values of two character expressions.
Syntax
DIFFERENCE ( character_expression , character_expression )
Arguments:character_expression: Is an expression of type char or varchar. character_expression can also be of type text; however, only the first 8,000 bytes are significant.
Return Types:  Int
Example :
USE AdventureWorks;
GO
-- Returns a DIFFERENCE value of 4, the least possible difference.
SELECT SOUNDEX('Green'), SOUNDEX('Greene'), DIFFERENCE('Green','Greene');
GO
-- Returns a DIFFERENCE value of 0, the highest possible difference.
SELECT SOUNDEX('Blotchet-Halls'), SOUNDEX('Greene'), DIFFERENCE('Blotchet-Halls', 'Greene');
GO
Output:
----- ----- ----------- 
G650  G650  4           

(1 row(s) affected)
                        
----- ----- ----------- 
B432  G650  0           

(1 row(s) affected)

LEFT() 

Returns the left most characters of a string.
Syntax
LEFT(string, length) 
string
Specifies the string from which to obtain the left-most characters.

length
Specifies the number of characters to obtain.
Example :
SELECT LEFT('Marufuzzaman',5)  
OutPut
Maruf

RIGHT()

Returns the right most characters of a string.
Syntax  
RIGHT(string, length) 
string
Specifies the string from which to obtain the left-most characters.

length
Specifies the number of characters to obtain.
Example :
SELECT RIGHT('Md. Marufuzzaman',12)  
OutPut
Marufuzzaman 

LTRIM() 

Returns a character expression after it removes leading blanks.
Example :
SELECT LTRIM('   Md. Marufuzzaman') 
OutPut
Md. Marufuzzaman

RTRIM()

Returns a character string after truncating all trailing blanks.
Example : 
SELECT RTRIM('Md. Marufuzzaman    ') 
OutPut
Md. Marufuzzaman

REPLACE() 

Returns a string with all the instances of a substring replaced by another substring.
Syntax
REPLACE(find, replace, string)
Find
Specifies the string that contains the substring to replace all instances of with another.

Replace
Specifies the substring to locate.

String
Specifies the substring with which to replace the located substring.

Example :
SELECT REPLACE('The codeProject is ?.','?', 'your development resource')
OutPut:
 The codeProject is your development resource.

QUOTNAME()

Returns a Unicode string with the delimiters added to make the input string a valid Microsoft SQL Server delimited identifier.
Syntax
QUOTENAME ( 'character_string' [ , 'quote_character' ] )  
Arguments
' character_string '
Is a string of Unicode character data. character_string is sysname and is limited to 128 characters. Inputs greater than 128 characters return NULL.

' quote_character '
Is a one-character string to use as the delimiter. Can be a single quotation mark ( ' ), a left or right bracket ( [ ] ), or a double quotation mark ( " ). If quote_character is not specified, brackets are used.

Return Types: nvarchar(258)

Examples :
The following example takes the character string abc[]def and uses the [ and ] characters to create a valid SQL Server delimited identifier.

SELECT QUOTENAME('abc[]def')
OutPut:
[abc[]]def] 

REVERSE()

Returns a character expression in reverse order.
Example :
SELECT REVERSE('namazzufuraM .dM')
Output: 
 Md. Marufuzzaman 

CHARINDEX

CharIndex returns the first occurance of a string or characters within another string. The Format of CharIndex is given Below:
CHARINDEX ( expression1 , expression2 [ , start_location ] )
Here expression1 is the string of characters to be found within expression2. So if you want to search ij within the word Abhijit, we will use ij as expression1 and Abhijit as expression2. start_location is an optional integer argument which identifies the position from where the string will be searched. Now let us look into some examples :
SELECT CHARINDEX('SQL', 'Microsoft SQL Server') 
OUTPUT:

11

So it will start from 1 and go on searching until it finds the total string element searched, and returns its first position. The Result will be 0 if the searched string is not found.

We can also mention the Start_Location of the string to be searched.

EXAMPLE:
SELECT CHARINDEX('SQL', 'Microsoft SQL server has a great SQL Engine',12)
So in the above example we can have the Output as 34 as we specified the StartLocation as 12, which is greater than initial SQL position(11).

PATINDEX

As a contrast PatIndex is used to search a pattern within an expression. The Difference between CharIndex and PatIndex is the later allows WildCard Characters.
PATINDEX ( '%pattern%' , expression)
Here the first argument takes a pattern with wildcard characters like '%' (meaning any string) or '_' (meaning any character).

For Example
PATINDEX('%BC%','ABCD')

Output:
2

Another flexibility of PATINDEX is that you can specify a number of characters allowed within the Pattern. Say you want to find all of the records that contain the words "Bread", or "bread" in a string, You can use the following :
SELECT PATINDEX('%[b,B]read%', 'Tommy loves Bread') 
In this example, we mentioned both b and B in square brackets. The Result will be 13 which is same if we have searched in 'Tommy loves bread'.

LEN

Len is a function which returns the length of a string. This is the most common and simplest function that everyone use. Len Function excludes trailing blank spaces.
SELECT LEN('ABHISHEK IS WRITING THIS')
This will output 24, it is same when we write LEN('ABHISHEK IS WRITING THIS ') as LEN doesnt take trailing spaces in count.

STUFF


Stuff is another TSql Function which is used to delete a specified length of characters within a string and replace with another set of characters. The general syntax of STUFF is as below :

STUFF(character_expression1, start, length, character_expression2)Character_Expression1 represents the string in which the stuff is to be applied. start indicates the starting position of the character in character_expression1, length is the length of characters which need to be replaced. character_expression2 is the string that will be replaced to the start position.

Let us take an example :
SELECT STUFF('SQL SERVER is USEFUL',5,6,'DATABASE')

So the result will be :
SQL DATABASE is USEFUL

SUBSTRING


Substring returns the part of the string from a given characterexpression. The general syntax of Substring is as follows :

SUBSTRING(expression, start, length)
Here the function gets the string from start to length. Let us take an example below:
SELECT OUT = SUBSTRING('abcdefgh', 2, 3)
The output will be "bcd".
Note : substring also works on ntext, VARCHAR, CHAR etc.

LOWER / UPPER


Anoter simple but handy function is Lower / UPPER. The will just change case of a string expression. For Example,
SELECT UPPER('this is Lower TEXT') 

Output:
THIS IS LOWER TEXT

MS SQL Server Admin - Queries

Tables and Views

To get all tables, views, and system tables, the following SQL Server system stored procedure can be executed.

exec sp_tables '%'

To filter by database for tables only, for example master:

exec sp_tables '%', '%', 'master', "'TABLE'"

To filter by database and owner / schema for tables only, for example, master and dbo:

exec sp_tables '%', 'dbo', 'master', "'TABLE'"

To return only views, replace "'TABLE'" with "'VIEW'". To return only system tables, replace "'TABLE'" with "'SYSTEM TABLE'".

Schemas / Owners

Here are two examples for queries to get schema / owner information.

select distinct SCHEMA_NAME from INFORMATION_SCHEMA.SCHEMATA order by SCHEMA_NAME

select name from dbo.sysusers where islogin = 1 order by name

Procedures

This is a query to get all MS SQL Server procedures.

exec sp_stored_procedures '%'

The query can be filtered to return procedures for specific schemas / owners and databases by appending more information onto the procedure call, such as the following:

exec sp_stored_procedures '%', 'dbo', 'master'

Procedure Columns

This is a system stored procedure call to get the columns in a SQL Server procedure.

exec sp_sproc_columns 'get_employee_names', 'dbo', 'sample'

Functions

This is a query to get all MS SQL Server functions.

select ROUTINE_NAME from INFORMATION_SCHEMA.ROUTINES where upper(ROUTINE_TYPE) = 'FUNCTION'

Triggers

This is a query to get all MS SQL Server triggers.

select * from sysobjects where type = 'TR'

The query can be filtered to return triggers for a specific owner by appending a user_name call onto the where clause to the query.

select * from sysobjects where type = 'TR' and user_name(sysobjects.uid) = 'dbo'

Indexes

This is a query to get MS SQL Server indexes for a particular table. In this example, the table used is employee.

exec sp_helpindex 'employee'

Introduction and Overview ASP.NET


Introduction

This series of tutorials guides you through the steps required to create an ASP.NET Web Forms application using Visual Studio Express 2012 for Web and ASP.NET 4.5.
The application you'll create is named Wingtip Toys. It's a simplified example of a store front web site that sells items online. This tutorial series highlights several of the new features available in ASP.NET 4.5.
Comments are welcome, and we'll make every effort to update this tutorial series based on your suggestions.

Audience

The intended audience of this tutorial series is experienced developers who are new to ASP.NET Web Forms. A developer interested in this tutorial series should have the following skills:
  •  Familiar with an object oriented programming language
  •  Familiar with Web development concepts (HTML, CSS, JavaScript)
  •  Familiar with relational database concepts
  •  Familiar with n-tier architecture concepts

Application Features

The ASP.NET Web Form features presented in this series include:
  •  The Web Application Project (not Web Site Project)
  •  Web Forms
  •  Master Pages, Configuration
  •  Entity Framework Code First, LocalDB
  •  Request Validation
  •  Strongly Typed Data Controls, Model Binding, Data Annotations, and Value Providers
  •  OAuth and OpenID
  •  ASP.NET Membership, Configuration and Authorization
  •  Unobtrusive Validation
  •  Routing

Application Scenarios and Tasks

Tasks demonstrated in this first series include:
  •  Creating, reviewing and running the new project
  •  Creating the database structure
  •  Initializing and seeding the database
  •  Customizing the UI using styles, graphics and a master page
  •  Adding pages and navigation
  •  Displaying menu details and product data
  •  Creating a shopping cart
  •  Adding OpenID support
  •  Adding a payment method
  •  Including an administrator role and a user to the application
  •  Restricting access to specific pages and folder
  •  Uploading a file to the web application
  •  Implementing input validation
  •  Registering routes for the web application
  •  Implementing error handling and error logging

Overview

If you are new to ASP.NET Web Forms but have familiarity with programming concepts, you have the right tutorial. If you are already familiar with ASP.NET Web Forms, you can benefit from this tutorial series by the new features available in ASP.NET 4.5. If you are unfamiliar with programming concepts and ASP.NET Web Forms, see Getting Started on the ASP.NET Web site.
The following screen shots provide a quick view of the ASP.NET Web forms application that you will create in this tutorial series. When you run the application from Visual Studio Express 2012 for Web, you will see the following web Home page.

Optimizing Your Asp.Net Pages for Faster Loading and Better Performance

If you read the internet and all of the websites dedicated to Asp.Net you will inevitably read about the wonders of the DataGrid, DataList, and Repeater controls. While each of these has its place, if you are only displaying data there is a much faster and more efficient means to do so.

Let's say you have a page that displays articles based on a query string. Take my article pages for instance. Each article is stored in a database and displayed on the page based on the unique id of the article as stored in the database.

A normal asp page execution procedure goes something like this. The code queries the database based on the Article I.D. and then brings back that information to the page where you display it in the fashion that you would like. This is a fairly straight forward approach with asp and is done all the time.

So how do we speed up our asp.net pages?
 1>: Use Asp.Net Caching!

This is a no-brainer, and I won't go into the brilliance or details of asp.net caching here because at the time of this writing Google has 2,780,000 articles on the topic. Basically instead of querying the database each time the page is loaded you only query the database once and load that result into the system cache. Subsequent calls to load the page retrieve the data from the cache as opposed to the database which gives you an instant and considerable performance boost. You can then set the cache for how long the cache should store the information as well as many other features. If you are not using the cache, you should be whenever possible!

2>: If possible, do NOT use the standard Asp.Net controls.
That's right. The standard asp.net controls are designed for rapid development and not page performance. They allow you to design pages that grab and display data very quickly but their actual performance suffers because of the extra overhead which is there for ease and speed of development time and not page execution speed.
Instead, create either a User Control or even better yet a Web Custom Control which is by far the fastest performance wise and really quite easy to create and use.

3>: Use an SqlDataReader or even better yet use a set based command for Sql Server data retrieval and simply execute that one command against the database.
An asp.net SqlDataReader is a fast forward only datareader that closes the connection after it reads the last set of results. Now for my article pages we are only returning 1 particular result. In this case we would opt for the set based command. If you had more than 1 result returned, in your table of contents for instance, you would use the SqlDataReader because you are returning multiple sets of results.
Set based commands are stored procedures that bring back data through parameters as opposed to a result set which then in turn needs to be looped through to obtain your data. So instead of writing your stored procedure like the following which brings back 1 result set:

Select Title, Body, Author
From Articles
Where ArtID = 215

We can write it using a set based command like this.
Create Procedure mysp_GetArticle

@Title varchar(200) Output,
@Body varchar(8000) Output,
@Author varchar(500) Output

As

Select @Title = Title, @Body = Body, @Author = Author
From Articles
Where ArtID = 215

GO

The above query will return only the three parameters called for and not a result or record set so you don't have to then walk through the returned record set that has only 1 result in it anyway. This second little process of work decreases your performance so you should avoid it whenever possible. Combine this technique with the asp.net cache.

4>: Use Classes and ArrayLists as opposed to returning an SqlDataReader.

Create a class and then if there are more than one set of results store those results into individual instantiations of that class. Finally store each of those classes into an ArrayList. You can then store only that ArrayList into the asp.net cache. So instead of getting the results back from a SqlDataReader when loading your page you get them from the ArrayList which is stored in the cache. Nice huh?
Finally... you want to incorporate all of these techniques into your final results which would be performed in the following manner and sequence.
On the first time the page loads, query the database and return all of your data storing it into individual classes. Then store each of those classes into an ArrayList. If you only have one single result you may store only the class into the cache. Then take your ArrayList and store it into the cache.
Next create a Web Custom Control and pass the cached ArrayList to the custom control and loop out your data using the HtmlTextWriter which is very fast. Remember each subsequent call to load the page will be called from the cache which stores your ArraList of classes or your single class.
Certainly it takes a significant amount of additional coding to do it in this fashion, especially when you take proper error handling into consideration, but if you follow this approach your pages will be screeching fast, you will immediately notice the difference, and your asp.net pages will execute in the proper sequence - Data handling in the PageLoad function and the html display in the PageRender function.

Tuesday, February 19, 2013

it allows a search parameter to be used on any part or parts of the server+database+schema+table names:

SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName nvarchar(4000))
DECLARE @Search nvarchar(4000)
       ,@SQL   nvarchar(4000)
SET @Search='login' --all rows
SET @SQL='select @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id WHERE @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name LIKE ''%'+ISNULL(@SEARCH,'')+'%'''

INSERT INTO @AllTables (CompleteTableName)
    EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY 1

Create New DataBase


ALTER PROCEDURE [Company].[Create_New_DataBase]
(@bd_name varchar(50),
@SchmaName VARCHAR(255),
 @CompanyName VARCHAR(255))
as
BEGIN
    IF NOT EXISTS(SELECT database_id FROM sys.databases WHERE name =@bd_name)
    BEGIN
        EXEC('Create DATABASE'+' '+ @bd_Name)
        BEGIN
            EXEC('USE'+' '+ @bd_Name)
           
            EXEC('SELECT * INTO  '+@bd_Name+'.'+@SchmaName+'.Banner FROM BlueBubble.Contents.Banner
            where CompanyName='+@CompanyName)
        end
    end
else
    print 'This Data base Is allready Existing'
end

Opps Part 1 : Abstraction

  Abstraction in C# is a fundamental concept of object-oriented programming (OOP) that allows developers t...