h1.post-title { color:orange; font-family:verdana,Arial; font-weight:bold; padding-bottom:5px; text-shadow:#64665b 0px 1px 1px; font-size:32px; } -->

Pages

Parts in CTE

Common Table Expression contains three core parts
The CTE name (this is what follows the WITH keyword) The column list (optional) The query (appears within parentheses after the AS keyword) The query using the CTE must be the first query appearing after the CTE.
Use CTE in SQL Server
Syntax of CTE:With Parameter
With T(<col Name>, <col name1>, <Col name2>)  --Column names for Temporary table
AS
(
SELECT A.<Col name>, E.<col name1>, E.<col name2> from <table_name> A
INNER JOIN <table_name> E ON E.<col name> = A.<col name>
)
SELECT * FROM T  --SELECT or USE CTE temporary Table
WHERE T.[col name]  > 50
ORDER BY T.<col name>
Use CTE in SQL Server
Syntax of CTE:Without Parameter
WITH MyCTE AS (SELECT c.[Col name] FROM [table_name] pc INNER JOIN [table_name] c ON c.[Col name] = pc.[Col name]) SELECT cte.[Col name], p.[Col name] FROM [table_name] p INNER JOIN [table_name].[Col name] ea ON ea.[Col name] = p.[Col name] INNER JOIN MyCTE cte ON cte.[Col name] = p.[Col name] INNER JOIN [table_name].PersonPhone ph ON ph.[Col name] = p.[Col name];

CTE in SQL Server

CTE in SQL Server

  • The common table expression (CTE) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement
  • You can also use a CTE in a CREATE VIEW statement, as part of the view’s SELECT query. In addition, as of SQL Server 2008, you can add a CTE to the new MERGE statement.

SQL DB Formatting

SQL DB Formatting

  • Use upper case for all SQL keywords 
  • SELECT, INSERT, UPDATE, WHERE, AND, OR, LIKE, etc. 
  • Indent code to improve readability 
  • Comment code blocks that are not easily understandable 
  • Use single-line comment markers(–) 
  • Reserve multi-line comments (/*.. ..*/) for blocking out sections of code 
  • Use single quote characters to delimit strings. 
  • Nest single quotes to express a single quote or apostrophe within a string 
  • For example, SET @sExample = ‘SQL”s Authority’ 
  • Use parentheses to increase readability WHERE (color=’red’ AND (size = 1 OR size = 2)) 
  • Use BEGIN..END blocks only when multiple statements are present within a conditional code segment.
  • Use one blank line to separate code sections. 
  • Use spaces so that expressions read like sentences. 
  • Format JOIN operations using indents 
  • Also, use ANSI Joins instead of old style joins 
  •  Place SET statements before any executing code in the procedure.

SQL DB Structure

SQL DB Structure

  • Each table must have a primary key.
  •  In most cases it should be an IDENTITY column named ID. 
  • Normalize data to third normal form. 
  • Do not compromise on performance to reach third normal form. Sometimes, a little de-normalization results in better performance. 
  • Do not use TEXT as a data type; use the maximum allowed characters of VARCHAR instead. 
  • In VARCHAR data columns, do not default to NULL; use an empty string instead. 
  • Columns with default values should not allow NULLs. 
  • As much as possible, create stored procedures on the same database as the main tables they will be accessing.

SQL DB General Rules

SQL DB General Rules

  • Do not use spaces in the name of database objects.
  •  Do not use SQL keywords as the name of database objects. 
  • In cases where this is necessary, surround the object name with brackets, such as [Year]. 
  • Do not prefix stored procedures with ‘sp_’2. 
  • Prefix table names with the owner name3.

SQL SERVER – Guidelines and Coding Standards

Use “Pascal” notation for SQL server Objects Like Tables, Views, Stored Procedures. Also tables and views should have ending “s”.
Example: UserDetails
If you have big subset of table group than it makes sense to give prefix for this table group. Prefix should be separated by _.
Example: Page_ UserDetails
Use following naming convention for Stored Procedure. sp<Application Name>_[<group name >_]<action type><table name or logical instance> Where action is: Get, Delete, Update, Write, Archive, Insert… i.e. verb
Example:spApplicationName_GetUserDetails
Use following Naming pattern for triggers: TR_<TableName>_<action><description>
Example:TR_UserDetails_UpdateUserName
Indexes : IX_<tablename>_<columns separated by_>
Example:IX_UserDetails_UserID
Primary Key : PK_<tablename>
Example:PK_UserDetails
Foreign Key : FK_<tablename_1>_<tablename_2>
Example:FK_UserDetails_Emails
Default: DF_<table name>_<column name>
Example:DF_ UserDetails_UserName
Normalize Database structure based on 3rd Normalization Form. Normalization is the process of designing a data model to efficiently store data in a database. (Read More Here)
Avoid use of SELECT * in SQL queries. Instead practice writing required column names after SELECT statement.
Example:SELECT Username, Password
FROM UserDetails
Use SET NOCOUNT ON at the beginning of SQL Batches, Stored Procedures and Triggers. This improves the performance of Stored Procedure. (Read More Here)
Properly format SQL queries using indents.
Example:SELECT Username, Password
FROM UserDetails ud
INNER JOIN Employee e ON e.EmpID = ud.UserID
Practice writing Upper Case for all SQL keywords.
Example:SELECT, UPDATE, INSERT, WHERE, INNER JOIN, AND, OR, LIKE.
It is common practice to use Primary Key as IDENTITY column but it is not necessary. PK of your table should be selected very carefully.
If “One Table” references “Another Table” than the column name used in reference should use the following rule :
Column of Another Table : <OneTableName> ID
Example:
If User table references Employee table than the column name used in reference should be UserID where User is table name and ID primary column of User table and UserID is reference column of Employee table.
Columns with Default value constraint should not allow NULLs.
Practice using PRIMARY key in WHERE condition of UPDATE or DELETE statements as this will avoid error possibilities.
Always create stored procedure in same database where its relevant table exists otherwise it will reduce network performance.
Avoid server-side Cursors as much as possible, instead use SELECT statement. If you need to use cursor then replace it next suggestion.
Instead of using LOOP to insert data from Table B to Table A, try to use SELECT statement with INSERT statement. (Read More Here)
INSERT INTO TABLE A (column1, column2)
SELECT column1, column2
FROM TABLE B
WHERE ....
Avoid using spaces within the name of database objects; this may create issues with front-end data access tools and applications. If you need spaces in your database object name then will accessing it surround the database object name with square brackets.
Example:[Order Details]
Do not use reserved words for naming database objects, as that can lead to some unpredictable situations. (Read More Here)
Practice writing comments in stored procedures, triggers and SQL batches, whenever something is not very obvious, as it won’t impact the performance.
Do not use wild card characters at the beginning of word while search using LIKE keyword as it results in Index scan.
Indent code for better readability. (Example)
While using JOINs in your SQL query always prefix column name with the table name. (Example). If additionally require then prefix Table name with ServerName, DatabaseName, DatabaseOwner. (Example)
Default constraint must be defined at the column level. All other constraints must be defined at the table level. (Read More Here)
Avoid using rules of database objects instead use constraints.
Do not use the RECOMPILE option for Stored Procedure unless there is specific requirements.
Practice to put the DECLARE statements at the starting of the code in the stored procedure for better readability (Example)
Put the SET statements in beginning (after DECLARE) before executing code in the stored procedure.

SQL SERVER – Stored Procedure Optimization Tips – Best Practices


  • Include SET NOCOUNT ON statement
  • Use schema name with object name
  • Do not use the prefix “sp_” in the stored procedure name
  • Use IF EXISTS (SELECT 1) instead of (SELECT *)
  • Use the sp_executesql stored procedure instead of the EXECUTE statement
  • Try to avoid using SQL Server cursors whenever possible
  • Keep the Transaction as short as possible
  • Use TRY-Catch for error handling

Auto Increment in VB.Net

Today, We will discuss about "How to Auto Increment in Vb.Net?"

Sub CustomerId()
 Dim strID As String = ""
 Dim St As String = ""
 CON = ConOpen()
 CMD = New SqlCommand("pass your sp or directquery", CON) 
 CMD.CommandType = CommandType.StoredProcedure
 CON.Open() 
 DR = CMD.ExecuteReader 
If DR.Read() Then
 strID = DR(0).ToString
 End If
 DR.Close()
 CON.Close()
 Dim INNO As Integer
 Dim IndID As String = ""
 Dim Num As Integer = "0001"
 Dim CPCode1 As String()
 Dim CPComp As String
 If strID = "" Then
 txtCustomerId.Text = "CI0000" & Num
 Else
 CPCode1 = strID.Split(New Char() {"I"c})
 For Each CPComp In CPCode1
 Console.WriteLine(CPComp)
 IndID = CPComp
 Next
 INNO = IndID + Num
 If INNO < 10 Then
 txtCustomerId.Text = "CI0000" & INNO
 ElseIf INNO >= 10 And INNO <= 99 Then
 txtCustomerId.Text = "CI000" & INNO
 ElseIf INNO >= 100 And INNO <= 999 Then
 txtCustomerId.Text = "CI00" & INNO
 ElseIf INNO >= 1000 And INNO <= 9999 Then
 txtCustomerId.Text = "CI0" & INNO
 ElseIf INNO >= 10000 Then
 txtCustomerId.Text = "CI" & INNO
 End If
 End If
 End Sub

In this Code, I create customer Id like "CI00001"

Entity Framework 6.0 Namespace

Entity Framework 6.0

  • Microsoft.Data.Entity.Design 
  • Microsoft.Data.Entity.Design.CodeGeneration 
  • Microsoft.Data.Entity.Design.DatabaseGeneration
  • Microsoft.Data.Entity.Design.DatabaseGeneration.Activities
  • Microsoft.Data.Entity.Design.DatabaseGeneration.OutputGenerators
  • Microsoft.Data.Entity.Design.Extensibility 
  • Microsoft.Data.Entity.Design.Templates 
  • Microsoft.Data.Entity.Design.UI.Views.Explorer 
  • Microsoft.Data.Entity.Design.VisualStudio.ModelWizard
  • Microsoft.Data.Entity.Design.VisualStudio.SingleFileGenerator
  • Microsoft.Data.Entity.Design.VisualStudio.TextTemplating
  • System.ComponentModel.DataAnnotations.Schema 
  • System.Data.Entity 
  • System.Data.Entity.Core 
  • System.Data.Entity.Core.Common 
  • System.Data.Entity.Core.Common.CommandTrees
  • System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder
  • System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder.Spatial
  • System.Data.Entity.Core.Common.EntitySql 
  • System.Data.Entity.Core.EntityClient 
  • System.Data.Entity.Core.Mapping 
  • System.Data.Entity.Core.Metadata.Edm 
  • System.Data.Entity.Core.Objects 
  • System.Data.Entity.Core.Objects.DataClasses 
  • System.Data.Entity.Infrastructure 
  • System.Data.Entity.Infrastructure.Annotations 
  • System.Data.Entity.Infrastructure.DependencyResolution 
  • System.Data.Entity.Infrastructure.MappingViews 
  • System.Data.Entity.Infrastructure.Pluralization 
  • System.Data.Entity.Migrations 
  • System.Data.Entity.Migrations.Builders 
  • System.Data.Entity.Migrations.Design 
  • System.Data.Entity.Migrations.History 
  • System.Data.Entity.Migrations.Infrastructure 
  • System.Data.Entity.Migrations.Model 
  • System.Data.Entity.Migrations.Sql 
  • System.Data.Entity.Migrations.Utilities 
  • System.Data.Entity.ModelConfiguration 
  • System.Data.Entity.ModelConfiguration.Configuration
  • System.Data.Entity.ModelConfiguration.Conventions 
  • System.Data.Entity.Spatial 
  • System.Data.Entity.SqlServer 
  • System.Data.Entity.SqlServerCompact 
  • System.Data.Entity.Validation 
  • XamlGeneratedNamespace

Entity Framework 6.0 Features

  1. Async Query and Save adds support for the task-based asynchronous patterns that were introduced in .NET 4.5. 
  2. Connection Resiliency enables automatic recovery from transient connection failures. 
  3. Code-Based Configuration gives you the option of performing configuration – that was traditionally performed in a config file – in code. 
  4. Dependency Resolution introduces support for the Service Locator pattern and we've factored out some pieces of functionality that can be replaced with custom implementations. 
  5. Interception/SQL logging provides low-level building blocks for interception of EF operations with simple SQL logging built on top. 
  6. Testability improvements make it easier to create test doubles for DbContext and DbSet when using a mocking framework or writing your own test doubles. 
  7. DbContext can now be created with a DbConnection that is already opened which enables scenarios where it would be helpful if the connection could be open when creating the context (such as sharing a connection between components where you can not guarantee the state of the connection). 
  8. Improved Transaction Support provides support for a transaction external to the framework as well as improved ways of creating a transaction within the Framework.
  9.  Enums, Spatial and Better Performance on .NET 4.0 - By moving the core components that used to be in the .NET Framework into the EF NuGet package we are now able to offer enum support, spatial data types and the performance improvements from EF5 on .NET 4.0.
  10.  Improved performance of Enumerable.Contains in LINQ queries. Improved warm up time (view generation), especially for large models.