Advantages:

Procedure to script your data (to generate INSERT statements from the existing data) 


This procedure generates INSERT statements using existing data from the given tables and views. Later, you can use these INSERT statements to generate the data. It's very useful when you have to ship or package a database application. This procedure also comes in handy when you have to send sample data to your vendor or technical support provider for troubleshooting purposes. 

Advantages:
  • Data from both tables and views can be scripted
  • No CURSORs are used
  • Table names and column names with spaces are handled
  • All datatypes are handled except images, large text and binary columns with more than 4 bytes
  • NULLs are gracefully handled
  • Timestamp columns are handled
  • Identity columns are handled
  • Very flexible and configurable
  • Non-dbo owned tables are handled 
  • Computed columns are handled
  • You can filter the rows for which you want to generate INSERTs

Usage:

Example 1:To generate INSERT statements for table 'titles':
EXEC sp_generate_inserts 'titles'
Example 2:To ommit the column list in the INSERT statement: (Column list is included by default)
NOTE: If you have too many columns, you are advised to ommit column list, as shown below, to avoid erroneous results
EXEC sp_generate_inserts 'titles', @Include_Column_List = 0
Example 3:To generate INSERT statements for 'titlesCopy' table from 'titles' table:
EXEC sp_generate_inserts 'titles', 'titlesCopy'
Example 4:To generate INSERT statements for 'titles' table for only those titles which contain the word 'Computer' in them:
EXEC sp_generate_inserts 'titles', @From = "from titles where title like '%Computer%'"
Example 5:To specify that you want to include TIMESTAMP column's data as well in the INSERT statement:
NOTE: By default TIMESTAMP column's data is not scripted
EXEC sp_generate_inserts 'titles', @Include_Timestamp = 1
Example 6: To print the debug information:
EXEC sp_generate_inserts 'titles', @debug_mode = 1
Example 7:If you are not the owner of the table, use @owner parameter to specify the owner name:
NOTE: To use this option, you must have SELECT permissions on that table
EXEC sp_generate_inserts Nickstable, @owner = 'Nick'
Example 8:To generate INSERT statements for the rest of the columns excluding images:
NOTE: When using this otion, DO NOT set @include_column_list parameter to 0
EXEC sp_generate_inserts imgtable, @ommit_images = 1
Example 9:To generate INSERT statements for the rest of the columns excluding IDENTITY column:
EXEC sp_generate_inserts mytable, @ommit_identity = 1
Example 10:To generate INSERT statements for the top 10 rows in the table:
EXEC sp_generate_inserts mytable, @top = 10
Example 11:To generate INSERT statements only with the columns you want:
EXEC sp_generate_inserts titles, @cols_to_include = "'title','title_id','au_id'"
Example 12:To generate INSERT statements by ommitting some columns:
EXEC sp_generate_inserts titles, @cols_to_exclude = "'title','title_id','au_id'"
Example 13:To avoid checking the foreign key constraints while loading data with INSERT statements:
NOTE: The @disable_constraints option will disable foreign key constraints, by assuming that the source data is valid and referentially sound
EXEC sp_generate_inserts titles, @disable_constraints = 1
Example 14:To avoid scripting data from computed columns:
EXEC sp_generate_inserts MyTable, @ommit_computed_cols = 1

NOTE: Please see the code and read the comments to understand more about how this procedure works!

To generate INSERT statements for all the tables in your database, execute the following query in that database, which will output the commands, that you need to execute for the same:

SELECT 'EXEC sp_generate_inserts ' + 
'[' + name + ']' + 
',@owner = ' + 
'[' + RTRIM(USER_NAME(uid)) + '],' + 
'@ommit_images = 1, @disable_constraints = 1'
FROM sysobjects 
WHERE type = 'U' AND 
OBJECTPROPERTY(id,'ismsshipped') = 0



Generate INSERT Statements

Procedure to script your data (to generate INSERT statements from the existing data)


This procedure generates INSERT statements using existing data from the given tables and views. Later, you can use these INSERT statements to generate the data. It's very useful when you have to ship or package a database application. This procedure also comes in handy when you have to send sample data to your vendor or technical support provider for troubleshooting purposes.


Create Procedure [dbo].[InsertScriptGenerator]
/*
exec sp_CreateDataLoadScript 'MyTable'
*/

@TblName varchar(128)
as

create table #a (id int identity (1,1), ColType int, ColName varchar(128))

insert #a (ColType, ColName)
select case when DATA_TYPE like '%char%' then 1 else 0 end ,
COLUMN_NAME
from information_schema.columns
where TABLE_NAME = @TblName
order by ORDINAL_POSITION


if not exists (select * from #a)
begin
raiserror('No columns found for table %s', 16,-1, @TblName)
return
end

declare @id int ,
@maxid int ,
@cmd1 varchar(7000) ,
@cmd2 varchar(7000)

select @id = 0 ,
@maxid = max(id)
from #a

select @cmd1 = 'select '' insert ' + @TblName + ' ( '
select @cmd2 = ' + '' select '' + '
while @id < @maxid
begin
select @id = min(id) from #a where id > @id

select @cmd1 = @cmd1 + ColName + ','
from #a
where id = @id

select @cmd2 = @cmd2
+ ' case when ' + ColName + ' is null '
+ ' then ''null'' '
+ ' else '
+ case when ColType = 1 then ''''''''' + ' + ColName + ' + ''''''''' else 'convert(varchar(20),' + ColName + ')' end
+ ' end + '','' + '
from #a
where id = @id

end


select @cmd1 = left(@cmd1,len(@cmd1)-1) + ' ) '' '
select @cmd2 = left(@cmd2,len(@cmd2)-8) + ' from ' + @tblName
select '/*' + @cmd1 + @cmd2 + '*/'


exec (@cmd1 + @cmd2)
drop table #a

SQLServer Code Library

NET Programming Standards and Naming ...

NET Programming Standards and Naming Conventions

Common .NET Naming Conventions

These are the industry-accepted standard naming conventions for J#, C# and VB.NET programs. For additional information, please see the MSDN help documentation and FX Cop. While individual naming conventions at organizations may vary (Microsoft only suggests conventions for public and protected items), the list below is quickly becoming the de-facto standard in the industry. Please note the absence of Hungarian Notation except in visual controls. These naming standards should find their way into all of your .NET development, including ASP.NET Web applications and .NET Windows Forms applications.

Note that while this document predates the online and printed standards documentation from Microsoft, everything below which indicates it is based on .NET library standards is consistent with that documentation. In areas where Microsoft has not provided guidance (Microsoft generally doesn't care what you do in private/non-exposed code. In fact, they aren't even consistant in their internal code in the .NET framework), de facto standards have emerged, and I have captured them here.

The "ux" naming convention for controls is something I have added and found to be helpful. It is not based on any official standards, but instead based upon a multitude of projects by my teams and others, as well as on-line discussions on the topic. While I strongly recommend that you follow Microsoft guidelines when present, I encourage you to try out the items marked as extensions below and see how they work for you before committing to them.


TypeStandard / ConventionExample
Namespaces

Standard Based Upon Microsoft .NET Library Standards

Pascal Case, no underscores. Use CompanyName.TechnologyName as root. If you don't have a company, use your domain name or your own initials. Note that any acronyms of three or more letters should be pascal case (Xml instead of XML) instead of all caps.

Why: This convention is consistent with the .NET Framework and is easy to read.

AppliedIS.TimeCard.BusinessRules
IrritatedVowel.Controllers
PeteBrown.DotNetTraining.InheritanceDemoPeteBrown.DotNetTraining.Xml
Assemblies

Standard Based Upon Microsoft .NET Library Standards

If the assembly contains a single name space, or has an entire self-contained root namespace, name the assembly the same name as the namespace.

Why: This convention is consistent with the .NET Framework and is easy to read. More importantly, however, it keeps your assembly names and namespaces lined up, making it really easy to figure out what is any particular assembly, and what assembly you need to reference for any given class.

AppliedIS.TimeCard.BusinessRules.dll
IrritatedVowel.Controllers.dll

Classes and Structs

Standard Based Upon Microsoft .NET Library Standards

Pascal Case, no underscores or leading "C" or "cls". Classes may begin with an "I" only if the letter following the I is not capitalized, otherwise it looks like an Interface. Classes should not have the same name as the namespace in which they reside. Any acronyms of three or more letters should be pascal case, not all caps. Try to avoid abbreviations, and try to always use nouns.

Why: This convention is consistent with the .NET Framework and is easy to read.

Widget
InstanceManager
XmlDocument
MainForm
DocumentForm
HeaderControl
CustomerListDataSet (typed dataset) 

Collection Classes

Standard Based Upon Microsoft .NET Library Standards

Follow class naming conventions, but add Collection to the end of the name

Why: This convention is consistent with the .NET Framework and is easy to read.

WidgetCollection
Delegate Classes

Standard Based Upon Microsoft .NET Library Standards

Follow class naming conventions, but add Delegate to the end of the name

Why: This convention is consistent with the .NET Framework and is easy to read.

WidgetCallbackDelegate
Exception Classes

Standard Based Upon Microsoft .NET Library Standards

Follow class naming conventions, but add Exception to the end of the name

Why: This convention is consistent with the .NET Framework and is easy to read.

InvalidTransactionException
Attribute Classes

Standard Based Upon Microsoft .NET Library Standards

Follow class naming conventions, but add Attribute to the end of the name

Why: This convention is consistent with the .NET Framework and is easy to read.

WebServiceAttribute
Interfaces

Standard Based Upon Microsoft .NET Library Standards

Follow class naming conventions, but start the name with "I" and capitalize the letter following the "I"

Why: This convention is consistent with the .NET Framework and is easy to read. It also distinguishes classes from interfaces, where (unlike in VB6) are truly different beings. This avoid name collisions as well, as it is quite common to have IFoo and a class named Foo that implements IFoo.

IWidget
Enumerations

Standard Based Upon Microsoft .NET Library Standards

Follow class naming conventions. Do not add "Enum" to the end of the enumeration name. If the enumeration represents a set of bitwise flags, end the name with a plural.

Why: This convention is consistent with the .NET Framework and is easy to read.

SearchOptions (bitwise flags)

AcceptRejectRule (normal enum)

Functions and Subs

Standard Based Upon Microsoft .NET Library Standards

Pascal Case, no underscores except in the event handlers. Try to avoid abbreviations. Many programmers have a nasty habit of overly abbreviating everything. This should be discouraged.

Functions and subs must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET

Why: This convention is consistent with the .NET Framework and is easy to read.

VB: Public Sub DoSomething(...)

C#: public void DoSomething(...)

Properties and Public * Member Variables

Standard Based Upon Microsoft .NET Library Standards

Pascal Case, no underscores. Try to avoid abbreviations. Members must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET.

Why: This convention is consistent with the .NET Framework and is easy to read.

VB: Public Property RecordID As Integer

C#: public int RecordID

Parameters

Standard Based Upon Microsoft .NET Library Standards

Camel Case. Try to avoid abbreviations. Parameters must differ by more than case to be usable from case-insensitive languages like Visual Basic .NET.

Why: This convention is consistent with the .NET Framework and is easy to read.

VB: ByRef recordID As Integer

C#: ref int recordID

Procedure-Level Variables

Standard Based Upon De facto Industry-Accepted Practices

Camel Case

Why: This convention is consistent with the .NET Framework and is easy to read. It also avoids naming collisions with class-level variables (see below)

VB: Dim recordID As Integer

C#: int recordID ;

Class-Level Private and Protected Variables

Standard Based Upon De facto Industry-Accepted Practices

Camel Case with Leading Underscore. In VB.NET, always indicate "Protected" or "Private", do not use "Dim". Use of "m_" is discouraged, as is use of a variable name that differs from the property by only case, especially with protected variables as that violates compliance, and will make your life a pain if you program in VB.NET, as you would have to name your members something different from the accessor/mutator properties.

Of all the items here, the leading underscore is really the only controversial one. I personally prefer it over straight underscore-less camel case for my private variables so that I don't have to qualify variable names with "this." to distinguish from parameters in constructors or elsewhere where I likely will have a naming collision. With VB.NET's case insensitivity, this is even more important as your accessor properties will usually have the same name as your private member variables except for the underscore.

As far as m_ goes, it is really just about aesthetics. I (and many others) find m_ ugly, as it looks like there is a hole in the variable name. It's almost offensive. I used to use it in VB6 all the time, but that was only because variables could not have a leading underscore. I couldn't be happier to see it go away.

Microsoft recommends against the m_ (and the straight _) even though they did both in their code. Also, prefixing with a straight "m" is right out. Of course, since they code mainly in C#, they can have private members that differ only in case from the properties. VB folks have to do something else. Rather than try and come up with language-by-language special cases, I recommend the leading underscore for all languages that will support it.

If I want my class to be fully CLS-compliant, I could leave off the prefix on any C# protected member variables. In practice, however, I never worry about this as I keep all potentially protected member variables private, and supply protected accessors and mutators instead.

Why: In a nutshell, this convention is simple (one character), easy to read (your eye is not distracted by other leading characters), and successfully avoids naming collisions with procedure-level variables and class-level properties.

VB: Private _recordID As Integer

C#: private int _recordID ;

Controls on Forms

An Extension to the Standards

In recent projects (since 2002 or so), I have taken to a single prefix for all my UI controls. I typically use "ux" (I used to use "ui", but it wasn't set apart well in intellisense). "ux" comes from my usual design abbreviations where it means "User eXperience", which has also since become a popular acronym. I have found this to be extremely helpful in that I get the desired grouping in the intellisense even better than if I use "txt", "lbl" etc. It also allows you to change combo boxes to text boxes etc. without having to change the names - something that happens often during initial prototyping, or when programming using highly iterative agile/xp methodologies.

Why: This convention avoids problems with changing control types (textboxes to drop-down lists, or simple text box to some uber textbox, or text box to date picker, for example), and groups the items together in intellisense. It is also much shorter than most Hungarian conventions, and definitely shorter and less type-dependent than appending the control type to the end of the variable name. I will use generic suffixes which allow me enough freedom to change them around.

"ux" prefix

uxUserID, uxHeader, uxPatientDateOfBirth, uxSubmit

Constants

Standard Based Upon Microsoft .NET Library Standards

Same naming conventions as public/private member variables or procedure variables of the same scope. If exposed publicly from a class, use PascalCase. If private to a function/sub, use camelCase..

Do not use SCREAMING_CAPS

Why: This convention is consistent with the .NET Framework and is easy to read. A sizable section of the Framework Design Guidelines is dedicated to why they chose not to go the SCREAMING_CAPS route. Using SCREAMING_CAPS also exposes more of the implementation than is necessary. Why should a consumer need to know if you have an enum, or (perhaps because they are strings) a class exposing public constants? In the end, you often want to treat them the same way, and black-box the implementation. This convention satisfies that criteria.

SomeClass.SomePublicConstant

localConstant

_privateClassScopedConstant

* Public class-level variables are universally frowned upon. It is considered to be a much better practice to use property procedures (accessors and mutators) to provide read and/or write access to a private member variable. If you must expose a member variable to other classes using "Public", follow the property naming conventions, but don't complain if your guilty conscience keeps you up at night ;-).

Please don't copy and paste these conventions on your own site. Feel free instead to link directly to this page. That way you get the ability to automatically get updates when I make them, as well as get that warm fuzzy you get by not copying someone else's work. Schools and accredited educational institutions can paste these conventions on their own sites if and only if they include a direct link to this page an an attribution for the source of the information from "Pete Brown's irritatedVowel.com". Thank you for respecting my wishes on this.

You Can find the standards for publicly exposed classes/properties etc at MSDN . If you want to run a tool to validate your code for public standards and required practices, download FXCop or use the analysis tools in Visual Studio 2005+.

 


.NET Programming Links


.NET Programming Links




Links












Good Mailing Lists
VISBAS-Lhttp://peach.ease.lsoft.com/archives/visbas-l.html
Developmentor .Net Listshttp://discuss.develop.com/

 












Useful Search Sites
CodeHound - Programmer's Search Enginehttp://www.CodeHound.com
Google Newsgroup Searchhttp://www.deja.com/

 






















































.NET and Other Resource Sites
.NET articles and Linkshttp://www.yoda.arachsys.com/csharp/
GotDotNet.comhttp://www.GotDotNet.com
WindowsForms.Nethttp://www.windowsforms.net/Default.aspx
Asp.Nethttp://www.asp.net/Default.aspx
Microsoft Patterns and Practiceshttp://www.microsoft.com/resources/practices
C#.nethttp://www.csharp.net
CodeProject C# Sitehttp://www.codeproject.com/csharp/
.NET Spiderhttp://www.dotnetspider.com
IIS FAQshttp://www.iisfaq.com/
UDDI Resourceshttp://www.uddi.org/solutions.html
Microsoft VS.Net Homehttp://msdn.microsoft.com/vstudio/
.Net Hostinghttp://www.brinkster.com
OpenWave SDK (Phone Emulator)http://www.openwave.com/products/developer_products/
.NET Rocks Talk Showhttp://www.dotnetrocks.com/
A site with tons of connection strings (nice!)http://www.connectionstrings.com
MSDN TVhttp://msdn.microsoft.com/msdntv/

 


















Specific Articles of Interest
Older Web Services vs. Remoting Performance Comparisonhttp://msdn.microsoft.com/webservices/building/default.aspx?pull=/library/en-us/dnbda/html/bdadotnetarch14.asp
Death of the Browser - Why you should use Windows Formshttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnadvnet/html/vbnet10142001.asp
Gang of Four (GoF) Patterns for .Net/C#http://www.dofactory.com/Patterns/Patterns.aspx
Article on Creating HttpHandlers and HttpModules in .Nethttp://www.15seconds.com/issue/020417.htm

 


















Installation and Deployment
.NET Framework Bootstrap Installerhttp://microsoft.com/downloads/details.aspx?FamilyId=66350891-D15B-446B-BD69-F7F849224A00&displaylang=en
Windows Updater Application Blockhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/updater.asp?frame=true
How to Distribute Config Files to Smart Clients (Windows Forms Apps) via the Webhttp://www.ondotnet.com/pub/a/dotnet/2003/01/27/ztd.html
Windows Forms Deployment Optionshttp://www.windowsforms.net/Default.aspx?tabindex=3&tabid=40#Deployment

 

















Standards and Specifications
C# ECMA Spechttp://www.ecma-international.org/publications/standards/ECMA-334.HTM
C# 2.0 Spechttp://msdn.microsoft.com/vcsharp/team/language/default.aspx
WSDL Spechttp://www.w3.org/TR/wsdl
For programming standards and naming conventions, see the link on the left menu.

 


 














Whidbey (VS .NET 2005) Information
MSDN Whidbey Site (VS .NET 2005)http://msdn.microsoft.com/vstudio/whidbey/default.aspx
The Whidbey Chronicles - IDE Enhancements for C# Developershttp://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20040219CSHARPDF/manifest.xml
ASP.NET 2.0http://www.asp.net/whidbey/

 


















Examples and Components
Terrarium (Better than Pong.Net!) ;-)http://www.gotdotnet.com/terrarium/whatis/
Google Web Servicehttp://www.google.com/apis/
Microsoft Exception Handling Application Blockhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/emab-rm.asp
VS.Net Power Toys and other Stuffhttp://www.gotdotnet.com/team/ide/

 












Additional Tools, Test-Driven Development, and Interesting Stuff
NUnit Unit Testing Frameworkhttp://www.nunit.org/
XML Acceleration Appliance (Good for Web Services)http://www.datapower.com/

 
























.NET Managed Data Providers
CoreLab MySQL Direct Managed Providerhttp://crlab.com/mysqlnet/
MySqlNet MySQL and Postgres Managed Providerhttp://sourceforge.net/projects/mysqlnet/
CoreLab Oracle Direct Managed Providerhttp://crlab.com/oranet/
Corelab Postgres Direct Managed Providerhttp://crlab.com/pgsqlnet/
Microsoft Oracle Managed Providerhttp://www.microsoft.com/downloads/details.aspx?FamilyId=4F55D429-17DC-45EA-BFB3-076D1C052524&displaylang=en
Oracle ODP Managed Providerhttp://otn.oracle.com/tech/windows/odpnet/content.html

 





















.NET Ports to Other Platforms and Enhancements/Research/Languages
Mono on Linuxhttp://www.go-mono.com/
Microsoft Shared Source CLI - Rotor (Free BSD, OS X, Win XP)http://msdn.microsoft.com/net/sscli
On the Death of Microsoft Shared Source CLI Community Sitehttp://weblogs.cs.cornell.edu/AllThingsDistributed/archives/000525.html
Old Generics Support in C# (SSCLI Gyro)http://research.microsoft.com/projects/clrgen/
Microsoft F#http://research.microsoft.com/projects/ilx/fsharp.aspx

 


.NET Best Practices

jQuery showing or hiding effects

jQuery showing or hiding effects


 In this article I explain some simple effects showing or hiding some elements on the page using jQuery.

In jQuery the two function show() and hide() simply work this.

Let's take example for show and hide div tag.
For that first takes two link for Show and Hide and div with some text.

<a href="#" id="btnShow">Show</a> 
<a href="#" id="btnHide">Hide</a>
<div>Hello Demo for showing & hiding div using jQuery.</div>

In jQuery put script for showing or hiding elements insode $(document).ready() function.

   <script src="http://code.jquery.com/jquery-latest.js" ></script>

   <script>
    $(document).ready(function(){
    
      $('#btnShow').click(function(){
      $('div').show("fast"); });

      $('#btnHide').click(function(){
      $("div").hide(1000); });
    });
   </script>

In above code simply show/hide <div> tag when btnShow click it show <div> tag and when btnHide click it hide <div> tag.

In above code you can see dollar sign"$" is nothing but a shorthand notation for find method in JQuery.

How to use Selector?

If you want to select any element in the page then you can use dollar sign "$" to get that element.

  • Element Selector : for selecting all matching tag or elements use $('tagname') like  $('div').
  • ID Selector : for selecting element with the given id attribute use $('#id') like $('#btnShow').so,(#) used for access the element with id.
  • CSS selector: for find all element with a CSS class use $('.ClassName') select all element with ClassName CSS class..

In jQuery one more event toggle( ) which handle both events show() and hide().If they are shown, toggle makes them hidden (using the hide method). If they are hidden, toggle makes them shown (using the show method).

<a href="#" id="btnToggle">Toggle</a>

 $('#btnToggle').click(function () {
   $('div').toggle("slow"); });

In above all events show(speed),hide(speed),toggle(speed) use can specify speed for showing and hiding elements.Speed may be "slow","normal","fast" or the number of milliseconds to run the animation (e.g. 1000).


jQuery Introduction

jQuery Introduction


jQuery is a new kind of JavaScript Library or FrameWork,created by John Resig in 2006.jQuery is most powerfull JavaScript Library.

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.jQuery is designed to change the way that you write JavaScript.

  • jQuery is Lightweight about 18KB in size 
  • jQuery support all major browser.Latest version of browser supports IE 6.0+,FireFox 3.0+,Safari 3.0+,Opera 9.0+.(cross Browser)
  • One thing I want to mentioned that jQuery cannot be "faster" than JavaScript because jQuery written in JavaScript.

How to use jQuery?

First download jQuery latest version (v.1.3.1) from jQuery.com and add javascript to your page.
or Just include javascript <script src="http://code.jquery.com/jquery-latest.js"></script> without download.


Let's take first example to show alert box on page load using jQuery:

 <html>
  <head>
    <script src="
http://code.jquery.com/jquery-latest.js"></script>
    
    <script type="text/javascript">
     $(document).ready(function(){
      alert("Hello friend!!!");
     });
    
    </script>

  </head>
  <body>
   Alert Box On Page Load.
  </body>
  </html>

In above code $(document).ready event is work same as window.onload method of javascript.And executed when entire page and resources have been loaded in the DOM.All the events which you want in jQuery must call inside the $(document).ready() function.

So,The events in Jquery are bound to elements inside the $(document).ready() method.The elements get bound when document.ready is fired.


Also,you can add as many $(document).ready events on your page as you like but they are executed in the order they are added.


Find Nth highest record from table

Find Nth highest record from table


 In interview you can faced question like to give solution(query) for find Nth highest Record/number/salary from given employee table.

TO find out 3rd highest salary from table

--Find 3rd highest salary
SELECT TOP 1 salary 
FROM (
SELECT DISTINCT TOP 3 salary 
FROM tblSalary
ORDER BY salary DESC) S 
ORDER BY salary

General form to find to Nth highest salary from table

--Find Nth highest salary
SELECT TOP 1 salary FROM (
SELECT DISTINCT TOP N salary FROM tblSalary ORDER BY salary DESC) S 
ORDER BY salary

There are many solution to solve to this but above solution is easiest. 
Take other possible solution,

SELECT MIN(salary) FROM tblSalary WHERE salary IN
(SELECT DISTINCT TOP 3 salary FROM tblSalary ORDER BY salary DESC)

--or--

SELECT MIN(salary) FROM 
(SELECT DISTINCT TOP 3 salary FROM tblSalary ORDER BY salary DESC) S


SQL Server String Functions

SQL Server String Functions


String functions are mainly used to change the case of strings,concatenate strings,reverse strings,extract various part of strings and perform many other types of string manipulation.

In SQL Server there is a Several built-in string functions to perform string manipulations.All below functions takes string input value and return a string or numeric value.

ASCII : Returns the ASCII code value of a character(leftmost character of string).

Syntax: ASCII(character)

SELECT ASCII('a')->97 
SELECT ASCII('A')->65 
SELECT ASCII('1')->49
SELECT ASCII('ABC')->65

For Upper character 'A' to 'Z' ASCII value 65 to 90
For Lower character 'A' to 'Z' ASCII value 97 to 122
For digit '0' to '9' ASCII value 48 to 57

UNICODE : UNICODE function works just like ASCII function,except returns Unicode standard integer value. UNICODE could be useful if you are working with international character sets.

Syntax: UNICODE(character)

SELECT UNICODE('F')->70 
SELECT UNICODE('STRING FUNCTION')->83 (leftmost character of string)

LOWER : Convert character strings data into lowercase.

Syntax: LOWER(string)

SELECT LOWER('STRING FUNCTION')->string function

UPPER : Convert character strings data into Uppercase.

Syntax: UPPER(string)

SELECT UPPER('string function')->STRING FUNCTION

LEN : Returns the length of the character string.

Syntax: LEN(string)

SELECT LEN('STRING FUNCTION')->15

REPLACE : Replaces all occurrences of the second string(string2) in the first string(string1) with a third string(string3).

Syntax: REPLACE('string1','string2','string3')

SELECT REPLACE('STRING FUNCTION','STRING','SQL')->SQL Function

Returns NULL if any one of the arguments is NULL.

LEFT : Returns left part of a string with the specified number of characters counting from left.LEFT function is used to retrieve portions of the string.

Syntax: LEFT(string,integer)

SELECT LEFT('STRING FUNCTION', 6)->STRING

RIGHT : Returns right part of a string with the specified number of characters counting from right.RIGHT function is used to retrieve portions of the string.

Syntax: RIGHT(string,integer)

SELECT RIGHT('STRING FUNCTION', 8)->FUNCTION

LTRIM : Returns a string after removing leading blanks on Left side.(Remove left side space or blanks)

Syntax: LTRIM(string)

SELECT LTRIM('   STRING FUNCTION')->STRING FUNCTION

RTRIM : Returns a string after removing leading blanks on Right side.(Remove right side space or blanks)

Syntax: RTRIM( string )

SELECT RTRIM('STRING FUNCTION   ')->STRING FUNCTION

REVERSE : Returns reverse of a input string.

Syntax: REVERSE(string)

SELECT REVERSE('STRING FUNCTION')->NOITCNUF GNIRTS

REPLICATE : Repeats a input string for a specified number of times.

Syntax: REPLICATE (string, integer)

SELECT REPLICATE('FUNCTION', 3)->FUNCTIONFUNCTIONFUNCTION

SPACE : Returns a string of repeated spaces.The SPACE function is an equivalent of using REPLICATE function to repeat spaces.

Syntax: SPACE ( integer) (If integer is negative,a null string is returned.)

SELECT ('STRING') + SPACE(1) + ('FUNCTION')->STRING FUNCTION

SUBSTRING : Returns part of a given string.

SUBSTRING function retrieves a portion of the given string starting at the specified character(startindex) to the number of characters specified(length).

Syntax: SUBSTRING (string,startindex,length)

SELECT SUBSTRING('STRING FUNCTION', 1, 6)->STRING
SELECT SUBSTRING('STRING FUNCTION', 8, 8)->FUNCTION

STUFF : Deletes a specified length of characters and inserts another set of characters at a specified starting point.

STUFF function is useful to inserts a set of characters(string2) into a given string(string1) at a given position.

Syntax: STUFF (string1,startindex,length,string2)

SELECT STUFF('STRING FUNCTION', 1, 6, 'SQL')->SQL FUNCTION
SELECT STUFF('SQL FUNCTION', 5, 8, 'Tutorial')->SQL Tutorial

CHARINDEX : Returns the starting position of the specified string(string1) in a character string(string2).

Syntax: CHARINDEX (string1,string2 [,start_location ])

SELECT CHARINDEX('SQL','Useful SQL String Function')->8

SELECT CHARINDEX('SQL','Useful SQL String Function')->19

If string1 is not found within string2,CHARINDEX returns 0.

PATINDEX : PATINDEX function works very similar to CHARINDEX function.PATINDEX function returns the starting position of the first occurrence of a pattern in a specified string, or zeros if the pttern is not found.

Using PATINDEX function you can search pattern in given string using Wildcard characters(%).The % character must come before and after pattern.

Syntax: PATINDEX('%pattern%',string)

SELECT PATINDEX('%SQL%','Useful SQL String Function')->8

SELECT PATINDEX('Useful%','Useful SQL String Function')->1

SELECT PATINDEX('%Function','Useful SQL String Function')->19

If pattern is not found within given string,PATINDEX returns 0.


SQL Server Date Time Format

SQL Server Date Time Format


In SQL Server used Cast or Convert function to Format Date Time value or column into a specific date format.Both function are used to convert datetime to varchar or string.

CAST function Syntax: CAST(expression as data_type)

Let's convert current date time to varchar

select cast(getdate() as varchar)

CONVERT function is used to change or convert the DateTime formats.By using convert function you can get only Date part or only Time part from the datetime.

CONVERT Function Syntax: CONVERT(data_type,expression,date Format style)

Let's take Sql Server DateTtime styles example:

Format

Query

USA mm/dd/yy

select convert(varchar, getdate(), 1)

ANSI yy.mm.dd

select convert(varchar, getdate(), 2)

British/French dd/mm/yy

select convert(varchar, getdate(), 3)

German dd.mm.yy

select convert(varchar, getdate(), 4)

Italian dd-mm-yy

select convert(varchar, getdate(), 5)

dd mon yy

select convert(varchar, getdate(), 6)

Mon dd, yy

select convert(varchar, getdate(), 7)

USA mm-dd-yy

select convert(varchar, getdate(), 10)

JAPAN yy/mm/dd

select convert(varchar, getdate(), 11)

ISO yymmdd

select convert(varchar, getdate(), 12)

mon dd yyyy hh:miAM (or PM)

select convert(varchar, getdate(), 100)

mm/dd/yyyy

select convert(varchar, getdate(), 101)

yyyy.mm.dd

select convert(varchar, getdate(), 102)

dd/mm/yyyy

select convert(varchar, getdate(), 103)

dd.mm.yyyy

select convert(varchar, getdate(), 104)

dd-mm-yyyy

select convert(varchar, getdate(), 105)

dd mon yyyy

select convert(varchar, getdate(), 106)

Mon dd, yyyy

select convert(varchar, getdate(), 107)

hh:mm:ss

select convert(varchar, getdate(), 108)

Default + milliseconds mon dd yyyy hh:mi:ss:mmmAM (or PM)

select convert(varchar, getdate(), 109)

mm-dd-yyyy

select convert(varchar, getdate(), 110)

yyyy/mm/dd

select convert(varchar, getdate(), 111)

yyyymmdd

select convert(varchar, getdate(), 112)

Europe default + milliseconds dd mon yyyy hh:mm:ss:mmm(24h)

select convert(varchar, getdate(), 113) or select convert(varchar, getdate(), 13)

hh:mi:ss:mmm(24h)

select convert(varchar, getdate(), 114)

 


SQL server Date Time Function

SQL server Date Time Function


Date time functions allow manipulating columns with DATETIME/SMALLDATETIME data types. SQL server Date Time Function:

GETDATE and GETUTCDATE Functions

GETDATE and GETUTCDATE Functions are Nondeterministic function. Both functions returns the current date and time. GETDATE returns current system date and time of the computer where SQL Server is running.

GETUTCDATE returns current UTC time (Universal Time Coordinate or Greenwich Mean Time). The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which the instance of Microsoft SQL Server is running.

DATEADD Functions

DATEADD function is Deterministic function. DATEADD Function adds a certain interval of time to the specified date and time value.

Syntax: DATEADD (datepart , number, date )

DATEADD returns a new date time value based on adding an interval to the specified date and time value.

DATEDIFF Function

DATEDIFF function is Deterministic function. DATEDIFF () gives the difference between the two date values.

Syntax: DATEDIFF ( datepart , startdate , enddate )

DATEDIFF returns number of date and time boundaries crossed between two specified dates. In DATEDIFF function start date is subtracted from end date. If start date is later than end date, a negative value is returned.

DATEPART Function

To retrieve any part of date and time use DATEPART function.

Syntax: DATEPART ( datepart , date )

DATEPART function takes two arguments 1)part of the date that you want to retrieve and 2)date itself. The DATEPART function returns an integer that represents date part of specified date.

DATEPARTOutput
SELECT DATEPART(year, '2009-02-13 18:35:06.523')2009
SELECT DATEPART(quarter, '2009-02-13 18:35:06.523')1
SELECT DATEPART(month, '2009-02-13 18:35:06.523')2
SELECT DATEPART(dayofyear, '2009-02-13 18:35:06.523')44
SELECT DATEPART(day, '2009-02-13 18:35:06.523')13
SELECT DATEPART(week, '2009-02-13 18:35:06.523')7
SELECT DATEPART(weekday, '2009-02-13 18:35:06.523')6
SELECT DATEPART(hour, '2009-02-13 18:35:06.523')18
SELECT DATEPART(minute, '2009-02-13 18:35:06.523')35
SELECT DATEPART(second, '2009-02-1 18:35:06.523')6
SELECT DATEPART(millisecond, '2009-02-1 18:35:06.523')523

DATENAME Function

DATENAME Function returns a character string that represents date part of the specified date.

Syntax: DATENAME ( datepart , date )

DATENAME function takes two arguments same as DATEPART function 1) part of the date that you want to retrieve and 2) date itself.

If you want the name of month
SELECT DATENAME (
month, '2009-02-13 18:35:06.523')  => Output : February

If you want the name of week day
SELECT DATENAME (
weekday, '2009-02-13 18:35:06.523')  => Output : Friday

DAY, MONTH, and YEAR Functions

All of this DAY, MONTH, and YEAR functions takes a single date value as a argument. Each of this function returns an integer that represents respective portions of the date.

SELECT   DAY('2009-02-1 18:35:06.523') as 'Day', MONTH('2009-02-1 18:35:06.523') as 'Month', YEAR('2009-02-1 18:35:06.523') as 'Year'

Each of this functions equivalent to DATEPART function. Like DAY is equivalent to DATEPART (dd, date), MONTH is equivalent to DATEPART (mm, date) and YEAR is equivalent to DATEPART (yy, date).


SQL Server 2005 Query Analyzer shortc...

SQL Server 2005 Query Analyzer shortcuts.




Some important shortcuts list for query execute.Using this shortcuts you can save lots of time.


  • CTRL+E : Execute Query

  • F5 : Execute Query

  • ALT+BREAK : Cancel Query

  • CTRL+D : Display results in grid format

  • ALT+F1 : Database object info

  • CTRL+F5 : Parse query and check syntax

  • CTRL+K : Display/hide execution plan

  • CTRL+L : Display execution plan

  • CTRL+N : New Query window

  • CTRL+SHIFT+F : Save results to file

  • CTRL+Delete : Delete through the end of the line

.Net Shortcut Keys


.Net Shortcut Keys

Download

 ABC
1   
 Dotnet Shortcut Keys 
   
S.NoShortcut KeyFunction
5   
1Ctrl + Shift + NCreate New Project
72Ctrl + NCreate New File
83Ctrl + Shift + OOpen Project
94Ctrl + OOpen File
105Ctrl + SSave File
116Ctrl + Shift + SSave All File
127Alt + F  + XClose All
138Ctrl + ZUndo
149Ctrl + YRedo
1510Ctrl + XCut
1611Ctrl + CCopy
1712Ctrl + VPaste
1813Ctrl + ASelect All
1914Ctrl + FQuick Find
2015Ctrl + HQuick Replace
2116Ctrl + Shift + FFind in Files
2217Ctrl + Shift + HReplace in Files
2318Alt + F12Find Symbol
2419Ctrl + GGo To Line No.
2520Ctrl + PPrint
2621Ctrl + K, Ctrl + DFormat Document
2722Ctrl + K, Ctrl + FFormat Selection
2823Ctrl + Shift + UMake Upper Case
2924Ctrl + UMake Lower Case
3025Ctrl + K, Ctrl + \Delete Horizontal White Space
3126Ctrl + R, Ctrl + WView White Space
3227Ctrl + E, Ctrl + WWord Wrap
3328Ctrl + IIncremental Search
3429Ctrl + K, Ctrl + CComment Selection
3530Ctrl + K, Ctrl + UUncomment Selection
3631Ctrl + K, Ctrl + KToggel Book Mark
3732Ctrl + K, Ctrl + PPrevious Book Mark
3833Ctrl + K, Ctrl + NNew Book Mark
3934Ctrl + K, Ctrl + LClear Book Marks
4035Ctrl + Shift + K, Ctrl + Shift + PPrevious Book Mark in Folder
4136Ctrl + Shift + K, Ctrl + Shift + NNext Book Mark in Folder
4237Ctrl + K, Ctrl + HRemove Task List Shortcut
4338Ctrl + M, Ctrl + MToggel Out Lining Expansion
4439Ctrl + M, Ctrl + LToggel All Out Lining
4540Ctrl + M, Ctrl + PStop Out Lining
4641Ctrl + M, Ctrl + OCollapse to Definitions
4742Ctrl + K, Ctrl + MGenerate Method Stub
4843Ctrl + JList Members
4944Ctrl + Shift + SpaceParameter Info
5045Ctrl + K, Ctrl + IQuick Info
5146Alt + Right ArrowComplete Word
5247Ctrl + K, Ctrl + XInsert Snippet
5348Ctrl + K, Ctrl + SSurround With
5449Ctrl + Alt + SOpen Server Explorer
5550Ctrl + Alt + LOpen Solution Explorer
5651Ctrl + K, Ctrl + WBookmark Window
5752Ctrl + Shift + CClass View
5853Ctrl + \ , Ctrl + DCode Definition Window
5954Ctrl + Alt + JObject Browser
6055Ctrl + \ , Ctrl + EError List
6156Ctrl + Alt + OOutput
6257F4Properties window
6358Ctrl + \ , Ctrl + TTask List
6459Ctrl + Alt + XTool Box
6560Ctrl + Alt + ACommand Window
6661Ctrl + Alt + TDocument Outline
6762Ctrl + Shift + EResource View
6863Alt + F8Macro Explorer
6964Ctrl + Alt + RWeb Browser
7065Shift + Alt + EnterFull Screen
7166Ctrl + Shift + AAdd New Item
7267Shift + Alt + AAdd Existing Item
7368Ctrl + Shift + BBuild Solution
7469Ctrl + Alt + BBreak Points
7570F5Start Debugging
7671Ctrl + F5Start without Debugging
7772F10Step Over
7873F11Step In
7974F9Toggel Breakpoint
8075Ctrl + Shift + F9Delete All Break points
8176Ctrl + F1How Do I Help
8277Ctlr + Alt + F3Search
8378Ctrl + Alt + F1Contents
8479Ctrl + Alt + F2Index
8580Ctrl + Page UpView Designer
8681Ctrl + Page DownView Source
87