Thursday, June 13, 2013

Limiting SQL Query Result Set to few number

Hi All,

With TABLESAMPLE keyword we can restrict the Result of the SQL Query, where rows will be selected randomly from the table

For example one table have 10000 Rows, then with following query we will get approximate 10 % of the rows from table

SELECT * FROM [TABLE_NAME] TABLESAMPLE (10 PERCENT)

If the requirement is for the same set of records every time then we have to use REPEATABLE keyword at end with some seed value as shown below

SELECT * FROM [TABLE_NAME] TABLESAMPLE (10 PERCENT) REPEATABLE (205)

Tuesday, June 11, 2013

Find empty tables in SQL Database

Hi friends,

Here is the SQL code to find the Table Names and their owner of the Database where 0 records are available.

;With CTE(TableName, SchemaName, RowCnt)
As
(
 Select
T.Name As TableName, S.name As SchemaName, R.RowCnt
 from Sys.tables As T Inner Join
 (
Select
 ID, rowcnt As RowCnt
From SysIndexes Where IndId < 2
 ) As R On T.[Object_Id] = R.Id
 Inner Join sys.schemas As S On S.[schema_id] = T.[schema_id]
)

Select
 TableName, SchemaName
From CTE Where RowCnt = 0 

Thursday, June 06, 2013

Convert Money to Varchar using SQL

Hi,

When we try to convert Money variable to Varchar in SQL it automatically round off the value to 2 decimal places.

Following is example

DECLARE @UnitCost MONEY

SET @UnitCost = .0167

SELECT
   @UnitCost,
   CAST(@UnitCost AS VARCHAR(30)),
   CAST(@UnitCost AS DECIMAL(30, 4)),
   CAST(CAST(@UnitCost AS DECIMAL(30, 4)) AS VARCHAR(30))


but if you want value to be rounded off upto 4 decimal places then please see the following code

DECLARE @UnitCost MONEY

SET @UnitCost = .016789

SELECT
    @UnitCost, convert(varchar(10),@unitcost,2),

Thursday, April 25, 2013

How to add other ASP.Net Page events apart from Page_Load

Dear Friends,

When we add any new ASP.Net page in solution, By default we will get Page_Load event in the code behind file. But if we want to add other Page Life Cycle events and write some logic on it, here is the way to do it.

1.  Open Solution Explorer
2.  Select the Asp page on which you want to add events
3.  Right click on page and select View Component Designer as follows


4.  Then click on the Properties or Press F4 button and click on the yellow button to get list of all page life cycle event as follows


Happy coding.....

Monday, April 15, 2013

Sequence of ASP.Net events including Application, Page and Control

Application: BeginRequest

Application: PreAuthenticateRequest

Application: AuthenticateRequest

Application: PostAuthenticateRequest

Application: PreAuthorizeRequest

Application: AuthorizeRequest

Application: PostAuthorizeRequest

Application: PreResolveRequestCache

Application: ResolveRequestCache

Application: PostResolveRequestCache

Application: PreMapRequestHandler

Page: Construct

Application: PostMapRequestHandler

Application: PreAcquireRequestState

Application: AcquireRequestState

Application: PostAcquireRequestState

Application: PreRequestHandlerExecute

Page: AddParsedSubObject

Page: CreateControlCollection

Page: AddedControl

Page: AddParsedSubObject

Page: AddedControl

Page: ResolveAdapter

Page: DeterminePostBackMode

Page: PreInit

Control: ResolveAdapter

Control: Init

Control: TrackViewState

Page: Init

Page: TrackViewState

Page: InitComplete

Page: LoadPageStateFromPersistenceMedium

Control: LoadViewState

Page: EnsureChildControls

Page: CreateChildControls

Page: PreLoad

Page: Load

Control: DataBind

Control: Load

Page: EnsureChildControls

Page: LoadComplete

Page: EnsureChildControls

Page: PreRender

Control: EnsureChildControls

Control: PreRender

Page: PreRenderComplete

Page: SaveViewState

Control: SaveViewState

Page: SaveViewState

Control: SaveViewState

Page: SavePageStateToPersistenceMedium

Page: SaveStateComplete

Page: CreateHtmlTextWriter

Page: RenderControl

Page: Render

Page: RenderChildren

Control: RenderControl

Page: VerifyRenderingInServerForm

Page: CreateHtmlTextWriter

Control: Unload

Control: Dispose

Page: Unload

Page: Dispose

Application: PostRequestHandlerExecute

Application: PreReleaseRequestState

Application: ReleaseRequestState

Application: PostReleaseRequestState

Application: PreUpdateRequestCache

Application: UpdateRequestCache

Application: PostUpdateRequestCache

Application: EndRequest

Application: PreSendRequestHeaders

Application: PreSendRequestContent

Thursday, March 28, 2013

Disable UAC (User Account Control) Setting in Windows 8

Disable UAC (User Account Control) Setting in Windows 8

Hi,
This post i want to tell that in Window's 8 OS, although we Enable / Disable the UAC setting. It didn't affect in Registry (REGEDIT).

First we will see what is UAC
UAC (User Access Control):

It notifies us before changes are made to our PC that require administrative permissions. Mean once we change the UAC Setting from "Always Notify" to "Never Notify" we can Install Programs / Software which Window's OS thinks as harmful to system.

How to launch UAC Setting Screen: 

Open windows Run
Type "MSCONFIG" and press enter
Select Tools tab
Select "Change UAC Setting" tool and
Click on "Lauch" button

or

UAC Application Location:
C:\Windows\System32\UserAccountControlSettings.exe

Issue with Windows 8:

Althoug you change the UAC Setting with appliction. It didn't get changed in the Windows Registry, so in that case we have to change the value against concern Key in Registry as follows

Open the registry with REGEDIT command from Windows RUN and locate the following key in registry

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

here in right pane change the value for EnableLUA from 1 to 0 and restart you machine and enjoy...



Bye.


Monday, March 25, 2013

Computed Column in SQL Table


Computed Column:

We can add computed column in SQL Database tables where the value of one column is calculated from one or more columns of the same table. While creating table we have to use the column name for calculation of computed column.

Example:

I want to calculate the Square, Cube etc of the Number and store in database. For this i have the following create table statement

CREATE TABLE ROOTS
(
Num Int,
Sq As (Num * Num),
cub As (Num * Num * Num)
)

Here first column of the table definition is number for which I want to calculate the Square and Cube, so while adding second column as Sq (Square) I have used first column name Num * Num, and same way for cube.

Insert values in table.

Insert one value at a time into table.
INSERT INTO ROOTS VALUES (-1)

Insert more than one value into table.
INSERT INTO ROOTS VALUES (1) , (2) , (3) , (4) , (5) , (6) , (7) , (8)


One computed column we can not use for the calculation of another Computed column. If we try to create table definition as shown below

CREATE TABLE ROOTS
(
Num Int,
Sq As (Num * Num),
cub As (Sq * Num)
)

SQL Query Analyser will throw the following error

"Msg 1759
Computed column 'Sq' in table 'Roots' is not allowed to be used in another computed-column definition."

Friday, March 22, 2013

Take SQL Database Backup using C#


Take SQL Database Backup using C#

Hi Dear,

I have studied it from one of the Blog. Where using SQL Server SMO (Server Management Object) in C# how to take a SQL Server Database Backup. There are other ways also to take database backup like through wizard in SQL Management Studio.

1.  Add following references to your project

a.  Microsoft.SqlServer.ConnectionInfo
b.  Microsoft.SqlServer.Management.Sdk.Sfc
c.  Microsoft.SqlServer.Smo
d.  Microsoft.SqlServer.SmoExtended
e.  Microsoft.SqlServer.SqlEnum

2.  In your CS file add folliwing 2 Usings statements

a.  Microsoft.SqlServer.Management.Smo;
b.  using Microsoft.SqlServer.Management.Common;


following classes objects used to take Backup

a.  Backup
b.  BackupDeviceItem
c.  ServerConnection
d.  Server
e.  Database

and following enums are used for assgning values

a.  BackupTruncateLogType ( it contains NoTruncate, Truncate and TruncateOnly)
b.  BackupActionType (it contains Database, Files and Log)


Steps to take Backup:
1.  Create object of Backup Class
2.  Assign Action, Database, BackupSetDescrption, Checksum, Intialize, ContinueAfterError, ExpirationDate etc properties.
3.  Create object of BackupDeviceItem class
4.  Create object of ServerConnection class
5.  Create object of Server class with ServerConnection object
6.  Add object of BackupDeviceItem class as Device to object of Backup Class
7.  Call SqlBackup method of object of Backup Class
8.  Remove Device from object of Backup Class

Code:

public void BackupDatabase(string databaseName, string userName, string password, string serverName, string destinationPath)
            {

                try
                {                  
                    Backup BKP = new Backup();

                    BKP.Action = BackupActionType.Database;
                    BKP.BackupSetDescription = "BackUp of: " + databaseName.ToUpper() + "on" + DateTime.Now.ToString();
                    BKP.BackupSetName = databaseName.ToUpper();
                    BKP.Database = databaseName.ToUpper();

                    BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath + databaseName.ToUpper() + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".bak", DeviceType.File);

                    ServerConnection connection = new ServerConnection(serverName, userName, password);

                    Server sqlServer = new Server(connection);
                    sqlServer.ConnectionContext.StatementTimeout = 60 * 60;
                    Database db = sqlServer.Databases[databaseName];

                    BKP.Initialize = true;
                    BKP.Checksum = true;
                    BKP.ContinueAfterError = true;
                    BKP.Devices.Add(deviceItem);
                    BKP.Incremental = false;
                    BKP.ExpirationDate = DateTime.Now.AddDays(3);
                    BKP.LogTruncation = BackupTruncateLogType.Truncate;
                    BKP.FormatMedia = false;
                    BKP.SqlBackup(sqlServer);
                    BKP.Devices.Remove(deviceItem);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    Console.Read();
                }
            }
        }

Wednesday, March 20, 2013

SQL Server User Defined Functions

SQL Server User Defined Functions:

Functions accepts some parameters process and then returns some data. A function can have maximum 1024 input parameters. A parameter of the function can have a default value, the keyword DEFAULT must be specified when calling the function to get the default value. UDF are used to reduce the code blocks and it makes easy to maintain the function in case it needs to change.

UDF Types:

1.  Scalar value returning UDF
2.  Table value returning UDF
     a.  Inline Table
     b.  Multistatement Table

Scalar UDFs:

These UDFs returns a single value of a scalar datatypes such as integer, varchar(n), char(n), money, datetime, bit etc. Even UDF returns User Defined Data Types (UDDTs). All the datatypes can not be returned from the UDFs like text, ntext, image, timestamp etc.

How to Create Scalar UDF:

CREATE FUNCTION fnNeedToReorder
     (
         @ReorderLevel INT,
         @UnitsInStock INT,
         @UnitsOnOrder INT
     )
    RETURNS VARCHAR(3)
AS
BEGIN
    DECLARE @ReturnValue VARCHAR(3)
    IF ((@UnitsInStock + @UnitsOnOrder) - @ReorderLevel) < 0
        SET @ReturnValue = 'Yes'
    ELSE
        SET @ReturnValue = 'No'
    RETURN @ReturnValue
END


Use Scalar UDF:

SELECT    ProductID,
      ReorderLevel,
      UnitsInStock,
      UnitsOnOrder,
      fnNeedToReorder(ReorderLevel, UnitsInStock, UnitsOnOrder) AS NeedToReorder
FROM    Products

another alternative to use of above function can be computed column in table. In products table we can create one computed column called as NeedToReorder as shown below

ALTER TABLE Products
ADD  NeedToReorder AS fnNeedToReorder(ReorderLevel,UnitsInStock, UnitsOnOrder)

Few practical use of functions:

1.  Format the phone number in desired format
2.  Format a date in standard format MM/DD/YYYY
3.  Number in particular format ex. you need 1 to 100 number like 001,002,003 .. 100 format.


Table Valued UDFs:

With these UDFs we can return either inline or multistatement tables, a rowset can be returned via the table Data Type. As I told earlier with table valued UDF two types are inline and multistatement table value returing UDFs. Inline Table returning UDF returns rowset via SLQ server table datatype. Inline table returning UDF are defined with a single SELECT statement making up the body of the function. Such UDFs cannot contain additional T-SQL logic outside of the SQL SELECT statement that defines the table it will return. It is easier to create inline table compared to multistatement table returning UDFs.

Create Inline Table Valued UDF:

CREATE FUNCTION Fn_GetEmpByCity (@City VARCHAR(30))
       RETURNS TABLE
AS
RETURN
    (
        SELECT    FirstName, LastName, Address
        FROM    Employees
        WHERE    City = @City
    )

Use of Inline UDF:

Select * from Fn_GetEmpByCity('Ganesh')

Thursday, March 14, 2013

Second Largest salary

Find Second Largest salary of the employee..



SELECT *FROM Employee E1WHERE (N-1) = (SELECT COUNT(DISTINCT(E2.Salary))FROM Employee E2WHERE E2.Salary > E1.Salary)

Friday, March 08, 2013

Team Foundation Server Control 2010 commands

Hi Dear all,
Here I am giving some TFS commands to performs few basic activities like add files / folders to Team Foundation Version Control, checkin etc.

Command:     TF help
Description:   For command line description.

Command:     TF msdn
Description:   For full documentation in Microsoft Document Explorer.


TFS Commands:

TF ADD        
Adds new files and folders from a local file system location to Team Foundation version control.

TF BRANCH     
Copies an item or set of items, including metadata and version control history, from one location to another on the Team Foundation version control server and in the local workspace.

TF BRANCHES  
Displays the history of a branch for a specified file or folder.

TF CHANGESET
Displays information about a changeset and lets you change the associated attributes, such as comments and check-in notes.

TF CHECKIN
Commits pending changes in the current workspace to Team Foundation version control.

TF CHECKOUT
Makes the local file writable and changes its pending Change status to "edit" in the workspace. Edit is an alias for the Checkout command.

TF CERTIFICATES 
Configures how client authentication certificates are used when connecting to TFS through a secure connection.

TF CONFIGURE  
Enables an administrator to view and change the following configuration settings for a team project in the Source Control Settings dialog box:
               - Check-out settings
               - Check-in policies
               - Check-in notes

TF DELETE
Removes files and folders from Team Foundation version control and deletes them from the disk.

TF DESTROY
Destroys, or permanently deletes, version-controlled files from Team Foundation version control.

TF DIFF       
Compares, and if it is possible, displays differences between two files, files in two folders, or a shelveset and a local or server file.

TF DIR        
Displays all or part of the contents of Team Foundation version control.

TF FOLDERDIFF 
Display a visual representation of the differences between files in two server folders, in a server folder and a local folder, or in two local folders.

TF GET
Retrieves a read-only copy of a file from Team Foundation Server to the workspace and creates folders on disk to contain it.

TF HELP       
Displays a help topic to the command-line that contains detailed information about a Team Foundation command.

TF HISTORY 
Displays the revision history for one or more files and folders.

TF LEBEL      
Attaches a label to or removes a label from a version of a file or folder in Team Foundation version control.

TF LABLES     
Displays the list of labels in Team Foundation version control.

TF LOCALVERSIONS 
Displays the version of one or more items in a workspace.

TF LOCK       
Locks or unlocks a file or folder to deny or restore the permissions of users to check out an item for edit into a different workspace or to check in pending changes to an item from a different workspace.

TF MERGE      
Applies changes from one branch into another.

TF MERGES     
Displays detailed information about past merges between the specified source and destination branches.

TF MSDN      
Launches the Microsoft Document Explorer to the documentation page for the command.

TF PERMISSION 
Modifies the user access control list (ACL) and displays authorization settings for an item under version control.

TF PROPERTIES 
Displays information about items under version control.

TF PROXY      
Configures the proxy setting automatically or manually. You can also use the proxy command to add, delete, and list proxy server records.

TF RENAME     
Changes the name or the path of a file or folder. You can use the rename command or the alias move, to move a file or folder to a new location.

TF RESOLVE    
Resolves conflicts between changed items in your workspace and the latest or destination versions of items on the server.

TF ROLLBACK   
Rolls back the changes in a single or a range of changesets.

TF SHELVE     
Stores a set of pending changes, together with pending check-in notes, a comment, and a list of associated work items in Team Foundation Server without actually checking them into the version control server.

TF SHELVESETS 
Displays information about a set of shelved changes.

TF STATUS 
Displays information about pending changes to items in one or more workspaces.

TF UNDELETE   
Restores items that were previously deleted.

TF UNDO
Removes pending changes from a workspace.

TF UNLABEL    
Removes an item from an existing label in Team Foundation version control.

TF UNSHELVE   
Restores shelved file revisions, check-in notes, comments, and work item associations to the current workspace or removes  an existing shelveset from the server.

TF VIEW       
Retrieves a specific version of a file to a temporary folder on your computer and displays it.

TF WORKFOLD   
Creates, modifies, or displays information about the mappings between your workspace folders and the Team Foundation version control folders.

TF WORKSPACE  
Creates, deletes, displays, or modifies properties and mappings associated with a workspace.

TF WORKSPACES 
Displays information about workspaces in the system and updates cached information about a user name or computer name change on Team Foundation Server.


Enjoy.....

Saturday, January 05, 2013

How to add SAN Drives as SQL Resources / My Computer


How to add SAN Drives as SQL Resources / My Computer:

If your server has be allotted with new SAN drive, and which is not visible in My Computer and you are not able to perform any action on this drive please follow the given instructions.

1.       Once the SAN Drive is allotted to your server.
2.       First make Drive online using Disk Management utility
             
3.       Then format the Drive and allot Drive Letter.
4.       Then Open your FailOver Clustor Manager, and add a Disk as shown in below image

5.       Once a Disk is added to Storage, Select your server name and from Other Resources select SQL Server and right click to select Properties
       
6.       Then from Properties select Dependencies tab
       
7.       Insert required Drive using Insert Button
8.       Dependency Report can be seen as per below steps
       
9.       Finally your drive will be visible in My Computer.

Improve SQL Query performance

http://www.sqlsteps.com/sql-tutorial-improving-query-performance