SlideShare a Scribd company logo
1.Difference between VARCHAR and NVARCHAR in SQL Server

     S.No   Varchar[(n)]                         NVarchar[(n)]

     1      Basic Definition:                    Basic Definition:

            Non-Unicode Variable Length          UNicode Variable Length character
            character data type.                 data type. It can store both non-
                                                 Unicode and Unicode (i.e. Japanese,
            Example:                             Korean etc) characters.
            DECLARE @FirstName AS
            VARCHAR(50) = ‘UMAR’                 Example:
            SELECT @FirstName                    DECLARE @FirstName AS
                                                 NVARCHAR(50)= ‘UMAR’
                                                 SELECT @FirstName

     2      No. of Bytes required for each       No. of Bytes required for each
            character:                           character:

            It takes 1 byte per character        It takes 2 bytes per Unicode/Non-
                                                 Unicode character.
            Example:
            DECLARE @FirstName AS                Example:
            VARCHAR(50) = ‘UMAR’                 DECLARE @FirstName AS
            SELECT @FirstName AS                 NVARCHAR(50)= ‘UMAR’
            FirstName,DATALENGTH(@Firs           SELECT @FirstName AS
            tName) AS Length                     FirstName,DATALENGTH(@FirstNa
                                                 me) AS Length
            Result:
            FirstName Length                     Result:
            UMAR 4                               FirstName Length
                                                 UMAR 8

     3      Optional Parameter n range:          Optional Parameter n range:

            Optional Parameter n value can be Optional Parameter n value can be
            from 1 to 8000.Can store          from 1 to 4000.Can store maximum
            maximum 8000 Non-Unicode          4000 Unicode/Non-Unicode characters
            characters.

     4      If Optional Parameter n is not       If Optional Parameter n is not
            specified in the variable            specified in the variable declaration
            declaration or column                or column definition:
            definition:
                                                 If Optional parameter value n is not
            If Optional parameter value is not   specified in the variable declaration or
            specified in the variable            column definition then it is considered
            declaration or column definition     as 2
            then it is considered as 1.
                                                 Example:
            Example:                             DECLARE @firstName NVARCHAR
            DECLARE @firstName                   =‘UMAR’
            VARCHAR =‘UMAR’                      SELECT @firstName
SELECT @firstName                     FirstName,DATALENGTH(@firstNa
    FirstName,DATALENGTH(@firs            me) Length
    tName) Length
                                          Result:
    Result:                               FirstName Length
    FirstName Length                      U2
    U1

5   If Optional Parameter n is not        If Optional Parameter n is not
    specified in while using              specified in while using
    CAST/CONVERT functions:               CAST/CONVERT functions:

    When this optional parameter n is     When this optional parameter n is not
    not specified while using the         specified while using the CAST
    CAST/CONVERT functions, then          CONVERT functions, then it is
    it is considered as 30.               considered as 30.

    Example:                              Example:
    DECLARE @firstName                    DECLARE @firstName
    VARCHAR(35) =‘UMAR ASIA               NVARCHAR(35) =‘UMAR ASIA
    INDIA TAMIL NADU                      INDIA TAMIL NADU
    CUDDALORE’                            CUDDALORE’
    SELECT CAST(@firstName AS             SELECT CAST(@firstName AS
    VARCHAR)                              NVARCHAR)
    FirstName,DATALENGTH(CAS              FirstName,DATALENGTH(CAST(@f
    T(@firstName AS VARCHAR))             irstName AS NVARCHAR)) Length
    Length
                                          Result:
    Result:                               FirstName Length
    FirstName Length                      UMAR ASIA INDIA TAMIL NADU
    UMAR ASIA INDIA TAMIL                 CUD 60
    NADU CUD 30


7   Which one to use?                     Which one to use?

    If we know that data to be stored     If we know that data to be stored in the
    in the column or variable doesn’t     column or variable can have Unicode
    have any Unicode characters.          characters.

8   Storage Size:                         Storage Size:

    Takes no. of bytes equal to the no.   Takes no. of bytes equal to twice the
    of Characters entered plus two        no. of Characters entered plus two
    bytes extra for defining offset.      bytes extra for defining offset.
2.Difference between SQL Server and MySQL


     S.No   SQL Server                      MySQL

     1      Current Date and Time:          Current Date and Time:

            SELECT GETDATE()                SELECT NOW()

                                            Optionally: Use CURDATE() for the
                                            date only.

     2      Limiting Results:               Limiting Results:

            SELECT TOP 10 * FROM table      SELECT * FROM table WHERE id =
            WHERE id = 1                    1 LIMIT 10

     3      Date Field Default Value:       Date Field Default Value:

            DATETIME DEFAULT                DATETIME fields cannot have a
            GETDATE()                       default value, i.e. "GETDATE()"

                                            We must use your INSERT statement
                                            to specify CURDATE() for the field.

                                            Optionally: Use datatype
                                            TIMESTAMP DEFAULT
                                            CURRENT_TIMESTAMP

     4      Character Length:               Character Length:

            LEN()                           CHARACTER_LENGTH()
                                            Aliases: CHAR_LENGTH(),
                                            LENGTH()

     5      Character Replace:              Character Replace:

            REPLACE() works case            REPLACE() works case sensitively
            insensitively

     6      Trim Functions:                 Trim Functions:

            LTRIM() and RTRIM()             TRIM()

     7      String Concatenation:           String Concatenation:

            CONCATENATION USING +           CONCAT(string, string), which
            (Does not automatically cast    accepts two or more arguments.
            operands to compatible types)   (Automatically casts values into types
                                            which can be concatenated)

     8      Auto Increment Field            Auto Increment Field Definition:
            Definition:
tablename_id INTEGER
     tablename_id INT IDENTITY         AUTO_INCREMENT PRIMARY
     PRIMARY KEY                       KEY

9    Get a List of Tables:             Get a List of Tables:

     SP_TABLES                         SHOW TABLES

10   Get Table Properties:             Get Table Properties:

     HELP tablename                    DESCRIBE tablename

11   Get Database Version:             Get Database Version:

     SELECT @@VERSION                  SELECT VERSION()

12   Recordset Paging:                 Recordset Paging:

     Recordset paging done by client   Add to end of SQL: "LIMIT " &
     side-ADO (very involved)          ((intCurrentPage-1)*intRecsPerPage)
                                       & ", " & intRecsPerPage
                                       LIMIT: The first argument specifies
                                       the offset of the first row to return, and
                                       the second specifies the maximum
                                       number of rows to return. The offset of
                                       the initial row is 0 (not 1).

13   Get ID of Newest Inserted         Get ID of Newest Inserted Record:
     Record:
                                       Two step process:
     SET NOCOUNT ON; INSERT            1. Execute your statement:
     INTO...; SELECT                   objConn.Execute("INSERT INTO...")
     id=@@IDENTITY; SET                2. Set objRS =
     NOCOUNT OFF;                      objConn.Execute("SELECT
                                       LAST_INSERT_ID() AS ID")

14   Get a Random Record:              Get a Random Record:

     SELECT TOP 1 * FROM Users         SELECT * FROM Users ORDER BY
     ORDER BY NEWID()                  RAND() LIMIT 1

15   Generate a Unique GUID:           Generate a Unique GUID:

     SELECT NEWID()                    SELECT UUID()
3.Difference between SET QUOTED_IDENTIFIER ON and SET QUOTED_IDENTIFIER
OFF in SQL Server


     S.No   SET QUOTED_IDENTIFIER              SET QUOTED_IDENTIFIER OFF
            ON

     1      Characters Enclosed within         Characters Enclosed within double
            double quotes:                     quotes:

            is treated as Identifier           is treated as Literal

     2      Try using Characters Enclosed      Try using Characters Enclosed
            within double quotes as            within double quotes as identifier:
            identifier:
                                               Fails
            Works                              Example: Below statement to create a
            Example: Below statement to        table with table name “Table” Fails.
            create a table with table name     SET QUOTED_IDENTIFIER OFF
            “Table” succeeds.                  GO
            SET QUOTED_IDENTIFIER ON           CREATE TABLE dbo.”Table”
            GO                                 (id int,”Function” VARCHAR(20))
            CREATE TABLE dbo.”Table”           GO
            (id int,”Function”                 Error Message:
            VARCHAR(20)) GO                    Msg 102, Level 15, State 1,
                                               Line 1 Incorrect syntax near ‘Table’.

     3      Try using Characters Enclosed      Try using Characters Enclosed
            within double quotes as Literal:   within double quotes as Literal:

            Fails                              Works
            Example: Below statement fails.    Example: Below Statement Works.
            SET QUOTED_IDENTIFIER ON           SET QUOTED_IDENTIFIER OFF
            GO                                 GO
            SELECT “BIRADAR”                   SELECT “UMAR”
            Error Message:
            Msg 207, Level 16, State 1,
            Line 1 Invalid column name
            ‘UMAR’.

     4      Characters Enclosed within         Characters Enclosed within single
            single quotes:                     quotes:

            is treated as Literal              is treated as Literal
            Example:                           Example:
            SET QUOTED_IDENTIFIER ON           SET QUOTED_IDENTIFIER ON
            GO                                 GO
            SELECT ‘UMAR’                      SELECT ‘UMAR’


     5      How to find all the objects        How to find all the objects which are
            which are created with SET         created with SET
QUTOED_IDENTIFIER                   QUTOED_IDENTIFIER ON/OFF:
            ON/OFF:
                                                Below Statement can be used to find
            Below Statement can be used to      all the objects created with SET
            find all the objects created with   QUTOED_IDENTIFIER setting as
            SET QUTOED_IDENTIFIER               OFF:
            setting as ON:
                                                SELECT OBJECT_NAME (object_id)
            SELECT OBJECT_NAME                  FROM sys.sql_modules WHERE
            (object_id) FROM                    uses_quoted_identifier = 0
            sys.sql_modules WHERE
            uses_quoted_identifier = 1

4.Difference between DateTime and DateTime2 DataType


     S.No   DateTime                            DateTime2[(n)]

     1      Min Value: 1753-01-01 00:00:00      Min Value: 0001-01-01 00:00:00

     2      Max Value:                          Max Value:

            9999-12-31 23:59:59.997             9999-12-31 23:59:59.9999999

     3      Storage Size:                       Storage Size:

            8 Bytes                             6 to 8 bytes

                                                Note: Parameter n is optional and if it
                                                is not specified then fractional seconds
                                                precision is 7 digit and it can be from 0
                                                to 7 digit.
                                                For fractional seconds precision <3,
                                                takes 6 bytes
                                                For fractional seconds precision 3 or 4
                                                it will take 7 bytes
                                                For fractional seconds precision >4 it
                                                will take 8 bytes

     4      Usage:                              Usage:

            Declare @now datetime               Declare @now datetime2(7)

     5      Current Date and Time               Current Date and Time function:
            function:
                                                SYSDATETIME()- It returns DB
            GetDate() – It returns DB Current   Current Date and Time of DateTime2
            Date and Time of DateTime Data      Data Type
            Type
                                                Example: SELECT SYSDATETIME()
            Example: SELECT GETDATE()           Result: 2011-09-16 13:23:18.7676720
Result: 2011-09-16 13:23:18.767

      6      +/- days:                          +/- days:

             WORKS                              FAILS – Need to use only DateAdd
             Example: DECLARE                   function
             @nowDateTime DATETIME =            Example: DECLARE
             GETDATE()                          @nowDateTime2 DATETIME2=
             SELECT @nowDateTime + 1            SYSDATETIME()
             Result: 2011-09-17 13:44:31.247    SELECT @nowDateTime2+1
                                                Result: Msg 206, Level 16, State 2,
                                                Line 2
                                                Operand type clash: datetime2 is
                                                incompatible with int

      7      Compliance:                        Compliance:

             Is not an ANSI/ISO compliant       Is an ANSI/ISO compliant

Please visit my blog @ http://onlydifferencefaqs.blogspot.in/

More Related Content

PDF
C# Basics Quick Reference Sheet
DOC
Brief Summary Of C++
PPTX
Ruby -the wheel Technology
PPT
PDF
0php 5-online-cheat-sheet-v1-3
PDF
Vba functions
PPT
Fast Forward To Scala
PDF
Hw1 rubycalisthenics
C# Basics Quick Reference Sheet
Brief Summary Of C++
Ruby -the wheel Technology
0php 5-online-cheat-sheet-v1-3
Vba functions
Fast Forward To Scala
Hw1 rubycalisthenics

What's hot (19)

PDF
ANSI C REFERENCE CARD
PDF
C Reference Card (Ansi) 2
PDF
C reference card
PDF
javaarray
PPT
Lecture 7
PDF
Wayfinder Breadcrumbs 1 1
PPT
String classes and its methods.20
PPT
C++ basics
PPTX
Introduction to Client-Side Javascript
PDF
Ruby_Basic
PDF
Module7
PPTX
Ruby Basics
PDF
Objectiveccheatsheet
PDF
The Great Scala Makeover
PPT
C Language Unit-3
PPT
Unit3 jwfiles
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PPTX
Advanced Python : Decorators
PPTX
Java fundamentals
ANSI C REFERENCE CARD
C Reference Card (Ansi) 2
C reference card
javaarray
Lecture 7
Wayfinder Breadcrumbs 1 1
String classes and its methods.20
C++ basics
Introduction to Client-Side Javascript
Ruby_Basic
Module7
Ruby Basics
Objectiveccheatsheet
The Great Scala Makeover
C Language Unit-3
Unit3 jwfiles
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Advanced Python : Decorators
Java fundamentals
Ad

Similar to Sql server difference faqs- 9 (20)

PDF
Sql server difference faqs- 4
PDF
Lession 5 the columns of a table
PPTX
Database Design Disasters
DOC
Sql All Tuts 2009
PDF
Sql tutorial
PDF
Sql tutorial
PDF
DP080_Lecture_2 SQL related document.pdf
PPTX
Sql Basics And Advanced
PDF
Difference between sql server 2008 and sql server 2012
PPT
Sql operators & functions 3
PDF
Sql wksht-2
PPT
Intro to tsql unit 5
PPT
Intro To TSQL - Unit 5
PPT
SQL Server 2000 Research Series - Transact SQL
PPTX
String function in my sql
PPT
PDF
012. SQL.pdf
PPT
e computer notes - Creating and managing tables
PPTX
String functions
PDF
Chris Bull's Bi Portfolio
Sql server difference faqs- 4
Lession 5 the columns of a table
Database Design Disasters
Sql All Tuts 2009
Sql tutorial
Sql tutorial
DP080_Lecture_2 SQL related document.pdf
Sql Basics And Advanced
Difference between sql server 2008 and sql server 2012
Sql operators & functions 3
Sql wksht-2
Intro to tsql unit 5
Intro To TSQL - Unit 5
SQL Server 2000 Research Series - Transact SQL
String function in my sql
012. SQL.pdf
e computer notes - Creating and managing tables
String functions
Chris Bull's Bi Portfolio
Ad

More from Umar Ali (20)

PDF
Difference between wcf and asp.net web api
PDF
Difference between ActionResult() and ViewResult()
PDF
Difference between asp.net mvc 3 and asp.net mvc 4
PDF
Difference between asp.net web api and asp.net mvc
PDF
Difference between asp.net web forms and asp.net mvc
PDF
ASP.NET MVC difference between questions list 1
ODT
Link checkers 1
PDF
Affiliate Networks Sites-1
PDF
Technical Video Training Sites- 1
PDF
US News Sites- 1
PDF
How to create user friendly file hosting link sites
PDF
Weak hadiths in tamil
PDF
Bulughul Maram in tamil
PDF
Asp.net website usage and job trends
PDF
Indian news sites- 1
PDF
Photo sharing sites- 1
PDF
File hosting search engines
PDF
Ajax difference faqs compiled- 1
PDF
ADO.NET difference faqs compiled- 1
PDF
Dotnet differences compiled -1
Difference between wcf and asp.net web api
Difference between ActionResult() and ViewResult()
Difference between asp.net mvc 3 and asp.net mvc 4
Difference between asp.net web api and asp.net mvc
Difference between asp.net web forms and asp.net mvc
ASP.NET MVC difference between questions list 1
Link checkers 1
Affiliate Networks Sites-1
Technical Video Training Sites- 1
US News Sites- 1
How to create user friendly file hosting link sites
Weak hadiths in tamil
Bulughul Maram in tamil
Asp.net website usage and job trends
Indian news sites- 1
Photo sharing sites- 1
File hosting search engines
Ajax difference faqs compiled- 1
ADO.NET difference faqs compiled- 1
Dotnet differences compiled -1

Recently uploaded (20)

PPTX
sap open course for s4hana steps from ECC to s4
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Approach and Philosophy of On baking technology
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Cloud computing and distributed systems.
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Electronic commerce courselecture one. Pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Encapsulation theory and applications.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
sap open course for s4hana steps from ECC to s4
Network Security Unit 5.pdf for BCA BBA.
Big Data Technologies - Introduction.pptx
Programs and apps: productivity, graphics, security and other tools
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Approach and Philosophy of On baking technology
Review of recent advances in non-invasive hemoglobin estimation
Chapter 3 Spatial Domain Image Processing.pdf
Cloud computing and distributed systems.
MYSQL Presentation for SQL database connectivity
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Electronic commerce courselecture one. Pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Agricultural_Statistics_at_a_Glance_2022_0.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
The Rise and Fall of 3GPP – Time for a Sabbatical?
Encapsulation theory and applications.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm

Sql server difference faqs- 9

  • 1. 1.Difference between VARCHAR and NVARCHAR in SQL Server S.No Varchar[(n)] NVarchar[(n)] 1 Basic Definition: Basic Definition: Non-Unicode Variable Length UNicode Variable Length character character data type. data type. It can store both non- Unicode and Unicode (i.e. Japanese, Example: Korean etc) characters. DECLARE @FirstName AS VARCHAR(50) = ‘UMAR’ Example: SELECT @FirstName DECLARE @FirstName AS NVARCHAR(50)= ‘UMAR’ SELECT @FirstName 2 No. of Bytes required for each No. of Bytes required for each character: character: It takes 1 byte per character It takes 2 bytes per Unicode/Non- Unicode character. Example: DECLARE @FirstName AS Example: VARCHAR(50) = ‘UMAR’ DECLARE @FirstName AS SELECT @FirstName AS NVARCHAR(50)= ‘UMAR’ FirstName,DATALENGTH(@Firs SELECT @FirstName AS tName) AS Length FirstName,DATALENGTH(@FirstNa me) AS Length Result: FirstName Length Result: UMAR 4 FirstName Length UMAR 8 3 Optional Parameter n range: Optional Parameter n range: Optional Parameter n value can be Optional Parameter n value can be from 1 to 8000.Can store from 1 to 4000.Can store maximum maximum 8000 Non-Unicode 4000 Unicode/Non-Unicode characters characters. 4 If Optional Parameter n is not If Optional Parameter n is not specified in the variable specified in the variable declaration declaration or column or column definition: definition: If Optional parameter value n is not If Optional parameter value is not specified in the variable declaration or specified in the variable column definition then it is considered declaration or column definition as 2 then it is considered as 1. Example: Example: DECLARE @firstName NVARCHAR DECLARE @firstName =‘UMAR’ VARCHAR =‘UMAR’ SELECT @firstName
  • 2. SELECT @firstName FirstName,DATALENGTH(@firstNa FirstName,DATALENGTH(@firs me) Length tName) Length Result: Result: FirstName Length FirstName Length U2 U1 5 If Optional Parameter n is not If Optional Parameter n is not specified in while using specified in while using CAST/CONVERT functions: CAST/CONVERT functions: When this optional parameter n is When this optional parameter n is not not specified while using the specified while using the CAST CAST/CONVERT functions, then CONVERT functions, then it is it is considered as 30. considered as 30. Example: Example: DECLARE @firstName DECLARE @firstName VARCHAR(35) =‘UMAR ASIA NVARCHAR(35) =‘UMAR ASIA INDIA TAMIL NADU INDIA TAMIL NADU CUDDALORE’ CUDDALORE’ SELECT CAST(@firstName AS SELECT CAST(@firstName AS VARCHAR) NVARCHAR) FirstName,DATALENGTH(CAS FirstName,DATALENGTH(CAST(@f T(@firstName AS VARCHAR)) irstName AS NVARCHAR)) Length Length Result: Result: FirstName Length FirstName Length UMAR ASIA INDIA TAMIL NADU UMAR ASIA INDIA TAMIL CUD 60 NADU CUD 30 7 Which one to use? Which one to use? If we know that data to be stored If we know that data to be stored in the in the column or variable doesn’t column or variable can have Unicode have any Unicode characters. characters. 8 Storage Size: Storage Size: Takes no. of bytes equal to the no. Takes no. of bytes equal to twice the of Characters entered plus two no. of Characters entered plus two bytes extra for defining offset. bytes extra for defining offset.
  • 3. 2.Difference between SQL Server and MySQL S.No SQL Server MySQL 1 Current Date and Time: Current Date and Time: SELECT GETDATE() SELECT NOW() Optionally: Use CURDATE() for the date only. 2 Limiting Results: Limiting Results: SELECT TOP 10 * FROM table SELECT * FROM table WHERE id = WHERE id = 1 1 LIMIT 10 3 Date Field Default Value: Date Field Default Value: DATETIME DEFAULT DATETIME fields cannot have a GETDATE() default value, i.e. "GETDATE()" We must use your INSERT statement to specify CURDATE() for the field. Optionally: Use datatype TIMESTAMP DEFAULT CURRENT_TIMESTAMP 4 Character Length: Character Length: LEN() CHARACTER_LENGTH() Aliases: CHAR_LENGTH(), LENGTH() 5 Character Replace: Character Replace: REPLACE() works case REPLACE() works case sensitively insensitively 6 Trim Functions: Trim Functions: LTRIM() and RTRIM() TRIM() 7 String Concatenation: String Concatenation: CONCATENATION USING + CONCAT(string, string), which (Does not automatically cast accepts two or more arguments. operands to compatible types) (Automatically casts values into types which can be concatenated) 8 Auto Increment Field Auto Increment Field Definition: Definition:
  • 4. tablename_id INTEGER tablename_id INT IDENTITY AUTO_INCREMENT PRIMARY PRIMARY KEY KEY 9 Get a List of Tables: Get a List of Tables: SP_TABLES SHOW TABLES 10 Get Table Properties: Get Table Properties: HELP tablename DESCRIBE tablename 11 Get Database Version: Get Database Version: SELECT @@VERSION SELECT VERSION() 12 Recordset Paging: Recordset Paging: Recordset paging done by client Add to end of SQL: "LIMIT " & side-ADO (very involved) ((intCurrentPage-1)*intRecsPerPage) & ", " & intRecsPerPage LIMIT: The first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1). 13 Get ID of Newest Inserted Get ID of Newest Inserted Record: Record: Two step process: SET NOCOUNT ON; INSERT 1. Execute your statement: INTO...; SELECT objConn.Execute("INSERT INTO...") id=@@IDENTITY; SET 2. Set objRS = NOCOUNT OFF; objConn.Execute("SELECT LAST_INSERT_ID() AS ID") 14 Get a Random Record: Get a Random Record: SELECT TOP 1 * FROM Users SELECT * FROM Users ORDER BY ORDER BY NEWID() RAND() LIMIT 1 15 Generate a Unique GUID: Generate a Unique GUID: SELECT NEWID() SELECT UUID()
  • 5. 3.Difference between SET QUOTED_IDENTIFIER ON and SET QUOTED_IDENTIFIER OFF in SQL Server S.No SET QUOTED_IDENTIFIER SET QUOTED_IDENTIFIER OFF ON 1 Characters Enclosed within Characters Enclosed within double double quotes: quotes: is treated as Identifier is treated as Literal 2 Try using Characters Enclosed Try using Characters Enclosed within double quotes as within double quotes as identifier: identifier: Fails Works Example: Below statement to create a Example: Below statement to table with table name “Table” Fails. create a table with table name SET QUOTED_IDENTIFIER OFF “Table” succeeds. GO SET QUOTED_IDENTIFIER ON CREATE TABLE dbo.”Table” GO (id int,”Function” VARCHAR(20)) CREATE TABLE dbo.”Table” GO (id int,”Function” Error Message: VARCHAR(20)) GO Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ‘Table’. 3 Try using Characters Enclosed Try using Characters Enclosed within double quotes as Literal: within double quotes as Literal: Fails Works Example: Below statement fails. Example: Below Statement Works. SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER OFF GO GO SELECT “BIRADAR” SELECT “UMAR” Error Message: Msg 207, Level 16, State 1, Line 1 Invalid column name ‘UMAR’. 4 Characters Enclosed within Characters Enclosed within single single quotes: quotes: is treated as Literal is treated as Literal Example: Example: SET QUOTED_IDENTIFIER ON SET QUOTED_IDENTIFIER ON GO GO SELECT ‘UMAR’ SELECT ‘UMAR’ 5 How to find all the objects How to find all the objects which are which are created with SET created with SET
  • 6. QUTOED_IDENTIFIER QUTOED_IDENTIFIER ON/OFF: ON/OFF: Below Statement can be used to find Below Statement can be used to all the objects created with SET find all the objects created with QUTOED_IDENTIFIER setting as SET QUTOED_IDENTIFIER OFF: setting as ON: SELECT OBJECT_NAME (object_id) SELECT OBJECT_NAME FROM sys.sql_modules WHERE (object_id) FROM uses_quoted_identifier = 0 sys.sql_modules WHERE uses_quoted_identifier = 1 4.Difference between DateTime and DateTime2 DataType S.No DateTime DateTime2[(n)] 1 Min Value: 1753-01-01 00:00:00 Min Value: 0001-01-01 00:00:00 2 Max Value: Max Value: 9999-12-31 23:59:59.997 9999-12-31 23:59:59.9999999 3 Storage Size: Storage Size: 8 Bytes 6 to 8 bytes Note: Parameter n is optional and if it is not specified then fractional seconds precision is 7 digit and it can be from 0 to 7 digit. For fractional seconds precision <3, takes 6 bytes For fractional seconds precision 3 or 4 it will take 7 bytes For fractional seconds precision >4 it will take 8 bytes 4 Usage: Usage: Declare @now datetime Declare @now datetime2(7) 5 Current Date and Time Current Date and Time function: function: SYSDATETIME()- It returns DB GetDate() – It returns DB Current Current Date and Time of DateTime2 Date and Time of DateTime Data Data Type Type Example: SELECT SYSDATETIME() Example: SELECT GETDATE() Result: 2011-09-16 13:23:18.7676720
  • 7. Result: 2011-09-16 13:23:18.767 6 +/- days: +/- days: WORKS FAILS – Need to use only DateAdd Example: DECLARE function @nowDateTime DATETIME = Example: DECLARE GETDATE() @nowDateTime2 DATETIME2= SELECT @nowDateTime + 1 SYSDATETIME() Result: 2011-09-17 13:44:31.247 SELECT @nowDateTime2+1 Result: Msg 206, Level 16, State 2, Line 2 Operand type clash: datetime2 is incompatible with int 7 Compliance: Compliance: Is not an ANSI/ISO compliant Is an ANSI/ISO compliant Please visit my blog @ http://onlydifferencefaqs.blogspot.in/