Functions in SQL Server 2005


SQL Server built-in functions are either deterministic or nondeterministic. Functions are deterministic when they always return the same result any time they are called by using a specific set of input values. Functions are nondeterministic when they could return different results every time they are called, even with the same specific set of input values.

Functions that take a character string input and return a character string output use the collation of the input string for the output. Functions that take no character inputs and return a character string use the default collation of the current database for the output. Functions that take multiple character string inputs and return a character string use the rules of collation precedence to set the collation of the output string

In this article I am going to explain about some SQL Server 2005 functions with examples. A function performs an operation and returns a value.  A function consists of the function name, followed by a set of parenthesis that contains any parameter or arguments required by the function. If a function requires two or more arguments you can separate them with commas.

Here are going to discuss about some string functions, numeric functions and date/time functions.

Note – I am using my own database table for examples. See database table in figure 1.

 

Figure 1.

String Functions

1.    LEN (string) – Returns the number of characters of the specified string expression, excluding trailing blanks.

Example:

use Vendor

GO

Select LEN(‘Raj’), LEN(‘Raj    ‘) FROM VENDOR WHERE VendorFName=’Raj’

GO

LEN doesn’t count length of spaces. So result looks like this.

 

 

2.    LTRIM (string) – LTRIM function to return a character expression after removing leading spaces.

Example:

use Vendor

GO

use Vendor

SELECT LTRIM(‘   Raj’)

FROM VENDOR WHERE VendorFName=’Raj’

Go

 

 

 

3.    RTRIM (string) – RTRIM function to return a character expression after removing trailing spaces.

Example:

use Vendor

GO

use Vendor

Select RTRIM(‘Raj     ‘)

FROM VENDOR WHERE VendorFName=’Raj’

GO

 

 

 

4.    LEFT (string, length) – Returns the specified number of characters from the beginning of the string.

Example:

use Vendor

SELECT VendorFName, VendorLName, LEFT(VendorFName, 1) + LEFT (VendorLName, 1) AS Initials FROM Vendor

 

 

 

5.    RIGTH (string, length) – Returns the specified number of characters from the end of the string.

Example:

use Vendor

SELECT VendorFName, VendorLName, RIGHT(VendorFName, 1) + RIGHT (VendorLName, 1) AS Initials FROM Vendor

 

 

 

6.    SUBSTRING (string, start, length) – Returns the specified number of characters from the string starting at the specified position.

Example:

use Vendor

GO

SELECT SUBSTRING(‘beniwal’, 2, 2) FROM VENDOR WHERE VendorFName=’Raj’

GO

 

 

 

7.    REPLACE (search, find, replace) – Returns the search string with all occurrences of the find string replaced with the replace string.

Example:

use Vendor

GO

use Vendor

SELECT REPLACE(‘Beniwal’, ‘Beniwal’, ‘Choudhary’)

FROM VENDOR WHERE VendorFName=’Raj’

GO

 

 

 

8.    REVERSE (string) – Returns the string with the character in reverse order.

Example:

use Vendor

GO

use Vendor

SELECT REVERSE(‘Raj’)

FROM VENDOR WHERE VendorFName=’Raj’

GO

 

 

 

9.    CHARINDEX (find, search [, start]) – Returns an integer that represents the position of the first occurrence of the find string in the search string starting at the specified position. If the starting position isn’t specified, the search starts at the beginning of the string. If the staring isn’t found, the functions returns zero.

Example:

use Vendor

GO

use Vendor

SELECT CHARINDEX(‘w’, ‘Beniwal’)

FROM VENDOR WHERE VendorFName=’Raj’

GO

 

 

 

10. PATINDEX (find, search [, start]) – PATINDEX is useful with text data types; it can be used in a WHERE clause in addition to IS NULL, IS NOT NULL, and LIKE (the only other comparisons that are valid on text in a WHERE clause). If either pattern or expression is NULL, PATINDEX returns NULL when the database compatibility level is 70. If the database compatibility level is 65 or earlier, PATINDEX returns NULL only when both pattern and expression are NULL.

Example:

use Vendor

GO

use Vendor

SELECT PATINDEX(‘%Krew%’, VendorLName)

FROM VENDOR WHERE VendorId=5

GO

 

 

 

11. LOWER (string) – Returns the string converted to lowercase letters.

Example:

use Vendor

GO

use Vendor

SELECT LOWER(‘Raj’)

FROM VENDOR WHERE VendorFName=’Raj’

GO

 

 

 

12. UPPER (string) – Returns the string converted to uppercase letters.

Example:

use Vendor

GO

use Vendor

SELECT UPPER(‘Raj’)

FROM VENDOR WHERE VendorFName=’Raj’

GO

 

 

 

13. SPACE (integer) – Returns the string with the specified number of space characters (blanks).

Example:

use Vendor

GO

use Vendor

SELECT VendorFName + ‘,’ + SPACE(2) + VendorLName

FROM VENDOR WHERE VendorFName=’Raj’

GO

 

 

Numeric Functions

1      ROUND (number, length, [function]) – Returns the number rounded to the precision specified by length. If length is positive, the digits to the right of the decimal point are rounded. If it’s negative the digits to the left of the decimal point are rounded. To truncate the number rather than round it code a non zero value for function.

Example:

USE Vendor

GO

–Used Round the estimates

SELECT ROUND(123.9994, 3), ROUND(123.9995, 3)

 

–Use ROUND and rounding approximations

SELECT ROUND(123.4545, 2), ROUND(123.45, -2)

 

–Use ROUND to truncate

SELECT ROUND(150.75, 0), ROUND(150.75, 0, 1)

 

GO

 

 

2      ISNUMERIC(expressions) – Returns a value of 1 (true) if the expression is a numeric value; returns a values of 0 (false) otherwise.

Example:

USE Vendor

GO

SELECT IsNumeric(VendorId) FROM Vendor

SELECT ISNumeric(VendorFName) FROM Vendor

GO

 

 

3      ABS (number) – Returns the absolute value of number.

Example:

USE Vendor

GO

SELECT ABS(-1.0), ABS(0.0), ABS(1.0)

GO

 

 

 

4      CEILING (number) – Returns the smallest integer that is greater than or equal to the number.

Example:

USE Vendor

GO

SELECT CEILING($123.45),CEILING($-123.45), CEILING($0.0)

GO

 

 

5      FLOOR (number) – Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.

Example:

USE Vendor

GO

SELECT FLOOR(123.45), FLOOR(-123.45), FLOOR($123.45)

GO

 

 

6      SQUARE (float_number) – Returns the square of the given expression.

Example:

USE Vendor

GO

DECLARE @h float, @r float

SET @h = 5

SET @r = 1

SELECT PI()* SQUARE(@r)* @h AS ‘Cyl Vol’

GO

 

 

7      SQRT (float_number) – Returns a square root of a floating-point number.

Example:

USE Vendor

GO

DECLARE @myvalue float

SET @myvalue = 1.00

WHILE @myvalue < 10.00

BEGIN

SELECT SQRT(@myvalue)

SELECT @myvalue = @myvalue + 1

END

GO

 

 

 

 

8      RAND ([seed]) – Returns a random float value from 0 through 1.

Seed

Is an integer expression (tinyint, smallint, or int) that specifies the seed value. If seed is not specified, Microsoft SQL Server 2000 assigns a seed value at random. For a given seed value, the result returned is always the same.

Example:

USE Vendor

GO

DECLARE @counter smallint

SET @counter = 1

WHILE @counter < 5

BEGIN

SELECT RAND() Random_Number

SET NOCOUNT ON

SET @counter = @counter + 1

SET NOCOUNT OFF

END

GO

 

Date/Time Functions:

 

1 GetDate () – Returns the current system date and time in the Microsoft SQL Server standard internal format for date time values.

Example:

USE Vendor

GO

SELECT GetDate()

GO

 

2      GETUTCDATE() – Returns the current UTC date and time based on the system’s clock and time zone setting. UTC (Universal Time Coordination) is the same as Greenwich Mean Time.

Example:

USE Vendor

GO

SELECT GETUTCDATE()

GO

 

 

3      DAY (date) – Returns the day of the month as an integer.

Example:

USE Vendor

GO

SELECT DAY(’03/12/1998′) AS ‘Day Number’

GO

 

 

4      MONTH (date) – Returns the month as an integer.

Example:

USE Vendor

GO

SELECT “Month Number” = MONTH(’03/12/1998′)

SELECT MONTH(0), DAY(0), YEAR(0)

GO

 

 

 

5      YEAR (date) – Returns the 4-digit year as an integer.

Example:

USE Vendor

GO

SELECT “Year Number” = YEAR(’03/12/1998′)

GO

 

 

 

6      DATENAME (datepart, date) – Returns an integer representing the specified date part of the specified date.

Example:

USE Vendor

GO

SELECT DATENAME(month, getdate()) AS ‘Month Name’

GO

 

 

 

7      DATEPART(datepart, date)

Is the parameter that specifies the part of the date to return? The table lists date parts and abbreviations recognized by Microsoft SQL Server.

Datepart Abbreviations
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw
hour hh
minute mi, n
second ss, s
millisecond ms

 

The week (wk, ww) datepart reflects changes made to SET DATEFIRST. January 1 of any year defines the starting number for the week datepart, for example: DATEPART(wk, ‘Jan 1, xxxx’) = 1, where xxxx is any year.

 

The weekday (dw) datepart returns a number that corresponds to the day of the week, for example: Sunday = 1, Saturday = 7. The number produced by the weekday datepart depends on the value set by SET DATEFIRST, which sets the first day of the week.

 

Date

 

Is an expression that returns a datetime or smalldatetime value, or a character string in a date format. Use the datetime data type only for dates after January 1, 1753. Store dates as character data for earlier dates. When entering datetime values, always enclose them in quotation marks. Because smalldatetime is accurate only to the minute, when a smalldatetime value is used, seconds and milliseconds are always 0.

 

If you specify only the last two digits of the year, values less than or equal to the last two digits of the value of the two digit year cutoff configuration option are in the same century as the cutoff year. Values greater than the last two digits of the value of this option are in the century that precedes the cutoff year. For example, if two digit year cutoff is 2049 (default), 49 is interpreted as 2049 and 2050 is interpreted as 1950. To avoid ambiguity, use four-digit years.

 

For more information about specifying time values, see Time Formats. For more information about specifying dates, see datetime and smalldatetime.

Example :

USE Vendor

GO

SELECT GETDATE() AS ‘Current Date’

SELECT DATEPART(month, GETDATE()) AS ‘Month Number’

SELECT DATEPART(m, 0), DATEPART(d, 0), DATEPART(yy, 0)

GO

 

 

8      DATEADD (datepart, number, date) – Returns the date that results from adding the specified number of datepart units to the date.

Example –

USE Vendor

GO

SELECT DATEADD(day, 21, PostedDate) AS timeframe FROM Vendor

GO

 

 

 

9      DATEDIFF (datepart, startdate, enddate) – Returns the number of datepart units between the specified start date and end date.

Example:

USE Vendor

GO

SELECT DATEDIFF(day, posteddate, getdate()) AS no_of_days

FROM Vendor WHERE VendorFName=’Raj’

GO

 

 

 

10   ISDATE (expression) – Returns a value of 1(true) if the expression is a valid date/time value; returns a value of 0(false) otherwise.

Example:

USE Vendor

GO

DECLARE @datestring varchar(8)

SET @datestring = ’12/21/98′

SELECT ISDATE(@datestring)

GO

 

 

More Functions –

1      CASE – Evaluate a list of conditions and returns one of multiple possible return expressions.

 

CASE has two formats:

  • The simple CASE function compares an expression to a set of simple expressions to determine the result.
  • The searched case function evaluates a set of boolean expressions to determine the result.

Syntax:

 

Simple CASE function:

CASE input_expression

WHEN when_expression THEN result_expression

[…n]

[

ELSE else_result_expression

]

END

 

Searched CASE function:

 

CASE

WHEN Boolean_expression THEN result_expression

[…n]

[

ELSE else_result_expression

]

END

 

Example:

use Vendor

GO

SELECT VendorId, VendorFName, VendorLName,

CASE VendorId

WHEN 1 THEN ‘This is vendor id one’

WHEN 2 THEN ‘This is vendor id two’

WHEN 3 THEN ‘This is vendor id three’

WHEN 4 THEN ‘This is vendor id four’

WHEN 5 THEN ‘this is vendor id five’

END AS PrintMessage

FROM Vendor

 

 

 

2      COALESCE – Returns the first nonnull expression among its arguments.

 

Syntax:

 

COALESCE (expression […n])

Example:

use Vendor

GO

SELECT PostedDate, COALESCE(PostedDate, ‘1900-01-01’) AS NewDate

FROM Vendor

 

 

 

3      ISNULL – Replaces NULL with the specified replacement value.

 

Syntax:

 

ISNULL (check_expression, replacement_value)

Example:

use Vendor

GO

SELECT PostedDate, ISNULL(PostedDate, ‘1900-01-01’) AS NewDate

FROM Vendor

GO

 

 

 

 

4      GROUPING – Is an aggregate function that causes an additional column to be output with a value of 1 when the row is added by either the CUBE or ROLLUP operator, or 0 when the row is not the result of CUBE or ROLLUP.Grouping is allowed only in the select list associated with a GROUP BY clause that contains either the CUBE or ROLLUP operator.

 

Syntax:  GROUPING (column_name)

Example –

Use Vendor

GO

SELECT royality, SUM(advance) ‘total advance’, GROUPING(royality) ‘grp’

FROM advance

GROUP BY royality

WITH ROLLUP

 

 

 

5      ROW_Number() – Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition

 

Syntax:  ROW_NUMBER ( )     OVER ([<partition_by_clause>] <order_by_clause>)

 

Note: The ORDER BY in the OVER clause orders ROW_NUMBER. If you add an ORDER BY clause to the SELECT statement that orders by a column(s) other than ‘Row Number’ the result set will be ordered by the outer ORDER BY.

Example:

Use Vendor

GO

SELECT VendorFName, VendorLName,

ROW_Number() Over(ORDER BY PostedDate) AS ‘Row Number’

FROM Vendor

GO

 

 

 

 

6      RANK () – Returns the rank of each row within the partition of a result set. The rank of a row is one plus the number of ranks that come before the row in question.

Syntax: RANK ( )    OVER ([< partition_by_clause >] < order_by_clause >)

 

Arguments: < partition_by_clause >

 

Divides the result set produced by the FROM clause into partitions to which the RANK function is applied. For the syntax of PARTITION BY, see OVER Clause (Transact-SQL).

 

< order_by_clause >

 

Determines the order in which the RANK values are applied to the rows in a partition. For more information, see ORDER BY Clause (Transact-SQL). An integer cannot represent a column when the < order_by_clause > is used in a ranking function.

Example:

Use Vendor

GO

SELECT VendorId, VendorFName, VendorLName,

RANK() Over(PARTITION BY PostedDate ORDER BY VendorId) AS ‘RANK’

FROM Vendor ORDER BY PostedDate DESC

GO

 

 

 

7      DENSE_RANK () – Returns the rank of rows within the partition of a result set, without any gaps in the ranking. The rank of a row is one plus the number of distinct ranks that come before the row in question.

 

Syntax:  DENSE_RANK ( )    OVER ([< partition_by_clause >] < order_by_clause >)

 

Arguments: < partition_by_clause >

 

Divides the result set produced by the FROM clause into partitions to which the DENSE_RANK function is applied. For the syntax of PARTITION BY, see OVER Clause (Transact-SQL).

 

< order_by_clause >

 

Determines the order in which the DENSE_RANK values are applied to the rows in a partition. An integer cannot represent a column in the <order_by_clause> that is used in a ranking function.

Example :

Use Vendor

GO

SELECT VendorId, VendorFName, VendorLName,

DENSE_RANK() OVER(PARTITION BY PostedDate ORDER BY VendorId) AS ‘DENSE RANK’

FROM Vendor ORDER BY PostedDate DESC

GO

 

NTILE (integer_expression) – Distributes the rows in an ordered partition into a specified number of groups. The groups are numbered, starting at one. For each row, NTILE returns the number of the group to which the row belongs.

Syntax: NTILE (integer_expression) OVER ([<partition_by_clause>] < order_by_clause >)

Arguments: integer_expression

Is a positive integer constant expression that specifies the number of groups into which each partition must be divided? integer_expression can be of type int, or bigint.

Note:

integer_expression can only reference columns in the PARTITION BY clause. integer_expression cannot reference columns listed in the current FROM clause.

<partition_by_clause>

Divides the result set produced by the FROM clause into partitions to which the RANK function is applied. For the syntax of PARTITION BY, see OVER Clause (Transact-SQL).

< order_by_clause >

Determines the order in which the NTILE values are assigned to the rows in a partition. For more information, see ORDER BY Clause (Transact-SQL). An integer cannot represent a column when the <order_by_clause> is used in a ranking function.

Example :

Use Vendor

GO

SELECT VendorFName, VendorLName,

NTILE(4) OVER(PARTITION BY PostedDate ORDER BY VendorId DESC) AS ‘Quartile’

FROM Vendor

GO

 

 

Introduction to JOINs – Basic of JOINs


INNER JOIN

This join returns rows when there is at least one match in both the tables.

OUTER JOIN

 

 

There are three different Outer Join methods.

LEFT OUTER JOIN
This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.

RIGHT OUTER JOIN
This join returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.

FULL OUTER JOIN
This join combines left outer join and right after join. It returns row from either table when the conditions are met and returns null value when there is no match.

CROSS JOIN

 

 

This join is a Cartesian join that does not necessitate any condition to join. The resultset contains records that are multiplication of record number from both the tables.

Additional Notes related to JOIN:

The following are three classic examples to display where Outer Join is useful. You will notice several instances where developers write query as given below.

SELECT t1.*
FROM Table1 t1
WHERE t1.ID NOT IN (SELECT t2.ID FROM Table2 t2)
GO

The query demonstrated above can be easily replaced by Outer Join. Indeed, replacing it by Outer Join is the best practice. The query that gives same result as above is displayed here using Outer Join and WHERE clause in join.

/* LEFT JOIN - WHERE NULL */
SELECT t1.*,t2.*
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL

The above example can also be created using Right Outer Join.

NOT INNER JOIN
Remember, the term Not Inner Join does not exist in database terminology. However, when full Outer Join is used along with WHERE condition, as explained in the above two examples, it will give you exclusive result to Inner Join. This join will give all the results that were not present in Inner Join.

You can download the complete SQL Script here, but for the sake of complicity I am including the same script here.

USE AdventureWorks
GO
CREATE TABLE table1
(ID INT, Value VARCHAR(10))
INSERT INTO Table1 (ID, Value)
SELECT 1,'First'
UNION ALL
SELECT 2,'Second'
UNION ALL
SELECT 3,'Third'
UNION ALL
SELECT 4,'Fourth'
UNION ALL
SELECT 5,'Fifth'
GO
CREATE TABLE table2
(ID INT, Value VARCHAR(10))
INSERT INTO Table2 (ID, Value)
SELECT 1,'First'
UNION ALL
SELECT 2,'Second'
UNION ALL
SELECT 3,'Third'
UNION ALL
SELECT 6,'Sixth'
UNION ALL
SELECT 7,'Seventh'
UNION ALL
SELECT 8,'Eighth'
GO
SELECT *
FROM Table1
SELECT *
FROM Table2
GO
USE AdventureWorks
GO
/* INNER JOIN */
SELECT t1.*,t2.*
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.ID = t2.ID
GO
/* LEFT JOIN */
SELECT t1.*,t2.*
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID
GO
/* RIGHT JOIN */
SELECT t1.*,t2.*
FROM Table1 t1
RIGHT JOIN Table2 t2 ON t1.ID = t2.ID
GO
/* OUTER JOIN */
SELECT t1.*,t2.*
FROM Table1 t1
FULL OUTER JOIN Table2 t2 ON t1.ID = t2.ID
GO
/* LEFT JOIN - WHERE NULL */
SELECT t1.*,t2.*
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL
GO
/* RIGHT JOIN - WHERE NULL */
SELECT t1.*,t2.*
FROM Table1 t1
RIGHT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t1.ID IS NULL
GO
/* OUTER JOIN - WHERE NULL */
SELECT t1.*,t2.*
FROM Table1 t1
FULL OUTER JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t1.ID IS NULL OR t2.ID IS NULL
GO
/* CROSS JOIN */
SELECT t1.*,t2.*
FROM Table1 t1
CROSS JOIN Table2 t2
GO
DROP TABLE table1
DROP TABLE table2
GO

I hope this article fulfills its purpose. I would like to have feedback from my blog readers.  Please suggest me where do you all want me to take this article next.

 

10 reasons why SQL Server 2008 is going to rock


10.  Plug-in model for SSMS.   SSMS 2005 also had a plug-in model, but it was not published, so the few developers that braved that environment were flying blind.  Apparently for 2008, the plug-in model will be published and a thousand add-ins will bloom.

9.  Inline variable assignment. I often wondered why, as a language, SQL languishes behind the times.  I mean, it has barely any modern syntactic sugar.  Well, in this version, they are at least scratching the the tip of the iceberg.

Instead of:

DECLARE @myVar int
SET @myVar = 5

you can do it in one line:

DECLARE @myVar int = 5

Sweet.

8.  C like math syntax.  SET @i += 5.  Enough said.  They finally let a C# developer on the SQL team.

7.  Auditing. It’s a 10 dollar word for storing changes to your data for later review, debugging or in response to regulatory laws.  It’s a thankless and a mundane task and no one is ever excited by the prospect of writing triggers to handle it.  SQL Server 2008 introduces automatic auditing, so we can now check one thing off our to do list.

6.  Compression.  You may think that this feature is a waste of time, but it’s not what it sounds like.  The release will offer row-level and page-level compression.  The compression mostly takes place on the metadata.  For instance, page compression will store common data for affected rows in a single place.

The metadata storage for variable length fields is going to be completely crazy: they are pushing things into bits (instead of bytes).  For instance, length of the varchar will be stored in 3 bits.

Anyway, I don’t really care about space savings – storage is cheap.  What I do care about is that the feature promised (key word here “promises”) to reduce I/O and RAM utilization, while increasing CPU utilization.  Every single performance problem I ever dealt with had to do with I/O overloading.  Will see how this plays out.  I am skeptical until I see some real world production benchmarks.

5.  Filtered Indexes. This is another feature that sounds great – will have to see how it plays out.  Anyway, it allows you to create an index while specifying what rows are not to be in the index.  For example, index all rows where Status != null.  Theoretically, it’ll get rid of all the dead weight in the index, allowing for faster queries.

4.  Resource governor. All I can say is FINALLY.  Sybase has had it since version 12 (that’s last millennium, people).  Basically it allows the DBA to specify how much resources (e.g. CPU/RAM) each user is entitled to.  At the very least, it’ll prevent people, with sparse SQL knowledge from shooting off a query with a Cartesian product and bringing down the box.

Actually Sybase is still ahead of MS on this feature.  Its ASE server allows you to prioritize one user over another – a feature that I found immensely useful.

3.  Plan freezing.  This is a solution to my personal pet peeve. Sometimes SQL Server decides to change its plan on you (in response to data changes, etc…).  If you’ve achieved your optimal query plan, now you can stick with it.  Yeah, I know, hints are evil, but there are situations when you want to take a hammer to SQL Server – well, this is the chill pill.

2.  Processing of delimited strings. This is awesome and I could have used this feature…well, always.  Currently, we pass in delimited strings in the following manner:

exec sp_MySproc 'murphy,35;galen,31;samuels,27;colton,42'

Then the stored proc needs to parse the string into a usable form – a mindless task.

In 2008, Microsoft introduced Table Value Parameters (TVP).

CREATE TYPE PeepsType AS TABLE (Name varchar(20), Age int)
DECLARE @myPeeps PeepsType
INSERT @myPeeps SELECT 'murphy', 35
INSERT @myPeeps SELECT 'galen', 31
INSERT @myPeeps SELECT 'samuels', 27
INSERT @myPeeps SELECT 'colton', 42exec sp_MySproc2 @myPeeps

And the sproc would look like this:

CREATE PROCEDURE sp_MySproc2(@myPeeps PeepsType READONLY) ...

The advantage here is that you can treat the Table Type as a regular table, use it in joins, etc.  Say goodbye to all those string parsing routines.

1. Intellisense in the SQL Server Management Studio (SSMS).  This has been previously possible in SQL Server 2000 and 2005 with Intellisenseuse of 3rd party add-ins like SQL Prompt ($195).  But these tools are a horrible hack at best (e.g. they hook into the editor window and try to interpret what the application is doing).

Built-in intellisense is huge – it means new people can easily learn the database schema as they go.

Steps to Debug stored procedure of SQL server 2008 using Visual Studio 2010


Perform all these steps on machine where SQL server is installed
1.  Window key + R and Write:  compmgmt.msc

2.  Above step will open computer management dialog, in the left pane expand tree view from system tools >> local users and groups >> groups. Double click “Administrators” which appear in the right pane, As shown below

3.   On double clicking Administrators following dialog appears, in which you have to add the user name from where you are going to connect to the server using visual studio 2010 and want to debug. So to add user click add button as shown below.

4.  When Add… button is clicked following dialog appears, in which you give user name and click ok as shown in below dialog box.

5.  Now switch to the visual studio 2010, and open “Server Explorer“, and then click “connect to database” button as shown below.

6.  Fill all the information in the “Add connection” dialog. As shown below.

7.  You can click “Test connection” button to test connection. As shown below


8.  Expand stored procedure folder under the SQL server name and double click the stored procedure which you want to debug for e.g. “addimg”, Now Double clicking it will result in displaying the script of the stored procedure. Then put the breakpoint in your desired location in the script. As shown below

9.  Now right click the same stored procedure and select “Step into Stored procedure” from the context menu which appear on right click, As shown below

10.  Following “Run stored procedure” dialog will appear in which you need to fill all the input parameters which are declared when the stored procedure is created.

11.   Bingo…..Success in debugging the stored procedure

 

Stored Procedures


Introduction

Stored procedures (sprocs) are generally an ordered series of Transact-SQL statements bundled into a single logical unit. They allow for variables and parameters, as well as selection and looping constructs. A key point is that sprocs are stored in the database rather than in a separate file.

Advantages over simply sending individual statements to the server include:

  1. Referred to using short names rather than a long string of text; therefore, less network traffiic is required to run the code within the sproc.
  2. Pre-optimized and precompiled, so they save an incremental amount of time with each sproc call/execution.
  3. Encapsulate a process for added security or to simply hide the complexity of the database.
  4. Can be called from other sprocs, making them reusable and reducing code size.

Parameterization

A stored procedure gives us some procedural capability, and also gives us a performance boost by using mainly two types of parameters:

  • Input parameters
  • Output parameters

From outside the sproc, parameters can be passed in either by position or reference.

Declaring Parameters

  1. The name
  2. The datatype
  3. The default value
  4. The direction

The syntax is :

@parameter_name [AS] datatype [= default|NULL] [VARYING] [OUTPUT|OUT]

Let’s now create a stored procedure named “Submitrecord”.

First open Microsoft SQL Server -> Enterprise Manager, then navigate to the database in which you want to create the stored procedure and select New Stored Procedure.

See the below Stored Procedure Properties for what to enter, then click OK.

Now create an application named Store Procedure in .net to use the above sprocs.

Stored Procedure.aspx page code

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml” &gt;
<head runat=”server”>
<title>Store Procedure</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Label ID=”Label1″ runat=”server” Text=”ID”></asp:Label>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox><br /><br />
<asp:Label ID=”Label2″ runat=”server” Text=”Password”></asp:Label>
<asp:TextBox ID=”TextBox2″ runat=”server”></asp:TextBox><br /><br />
<asp:Label ID=”Label3″ runat=”server” Text=”Confirm Password”></asp:Label>
<asp:TextBox ID=”TextBox3″ runat=”server”></asp:TextBox><br /><br />
<asp:Label ID=”Label4″ runat=”server” Text=”Email ID”></asp:Label>
<asp:TextBox ID=”TextBox4″ runat=”server”></asp:TextBox><br /><br /><br />
<asp:Button ID=”Button1″ runat=”server” Text=”Submit Record” OnClick=”Button1_Click” />
</div>
</form>
</body>
</html>

Stored Procedure.aspx.cs page code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
DataSet ds = new DataSet();
SqlConnection con;
//Here we declare the parameter which we have to use in our application
SqlCommand cmd = new SqlCommand();
SqlParameter sp1 = new SqlParameter();
SqlParameter sp2 = new SqlParameter();
SqlParameter sp3 = new SqlParameter();
SqlParameter sp4 = new SqlParameter();

protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)

{
con = new SqlConnection(“server=(local); database= gaurav;uid=sa;pwd=”);
cmd.Parameters.Add(“@ID”, SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add(“@Password”, SqlDbType.VarChar).Value = TextBox2.Text;
cmd.Parameters.Add(“@ConfirmPassword”, SqlDbType.VarChar).Value = TextBox3.Text;
cmd.Parameters.Add(“@EmailID”, SqlDbType.VarChar).Value = TextBox4.Text;
cmd = new SqlCommand(“submitrecord”, con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}

When we run the application, the window will look like this:

After clicking the submit button the data is appended to the database as seen below in the SQL Server table record:

 

 


1. What are the basic functions for master, msdb, model, tempdb and resource databases?

The master database holds information for all databases located on the SQL Server instance and is theglue that holds the engine together. Because SQL Server cannot start without a functioning masterdatabase, you must administer this database with care.
The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.
The tempdb holds temporary objects such as global and local temporary tables and stored procedures.
The model is essentially a template database used in the creation of any new user database created in the instance.
The resoure Database is a read-only database that contains all the system objects that are included with SQL Server. SQL Server system objects, such as sys.objects, are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user metadata.
2. What is Service Broker?

Service Broker is a message-queuing technology in SQL Server that allows developers to integrate SQL Server fully into distributed applications. Service Broker is feature which provides facility to SQL Server to send an asynchronous, transactional message. it allows a database to send a message to another database without waiting for the response, so the application will continue to function if the remote database is temporarily unavailable.

3. Where SQL server user names and passwords are stored in SQL server?

They get stored in System Catalog Views sys.server_principals and sys.sql_logins.

4. What is Policy Management?

Policy Management in SQL SERVER 2008 allows you to define and enforce policies for configuring and managing SQL Server across the enterprise. Policy-Based Management is configured in SQL Server Management Studio (SSMS). Navigate to the Object Explorer and expand the Management node and the Policy Management node; you will see the Policies, Conditions, and Facets nodes.

5. What is Replication and Database Mirroring?

Database mirroring can be used with replication to provide availability for the publication database. Database mirroring involves two copies of a single database that typically reside on different computers. At any given time, only one copy of the database is currently available to clients which are known as the principal database. Updates made by clients to the principal database are applied on the other copy of the database, known as the mirror database. Mirroring involves applying the transaction log from every insertion, update, or deletion made on the principal database onto the mirror database.

6. What are Sparse Columns?

A sparse column is another tool used to reduce the amount of physical storage used in a database. They are the ordinary columns that have an optimized storage for null values. Sparse columns reduce the space requirements for null values at the cost of more overhead to retrieve nonnull values.

7. What does TOP Operator Do?

The TOP operator is used to specify the number of rows to be returned by a query. The TOP operator has new addition in SQL SERVER 2008 that it accepts variables as well as literal values and can be used with INSERT, UPDATE, and DELETES statements.

8. What is CTE?

CTE is an abbreviation Common Table Expression. A Common Table Expression (CTE) is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query.

9. What is MERGE Statement?

MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is matched then just update it and when unmatched then insert it. One of the most important advantages of MERGE statement is all the data is read and processed only once.

10. What is Filtered Index?

Filtered Index is used to index a portion of rows in a table that means it applies filter on INDEX which improves query performance, reduce index maintenance costs, and reduce index storage costs compared with full-table indexes. When we see an Index created with some where clause then that is actually a FILTERED INDEX.

11. Which are new data types introduced in SQL SERVER 2008?

The GEOMETRY Type: The GEOMETRY data type is a system .NET common language runtime (CLR) data type in SQL Server. This type represents data in a two-dimensional Euclidean coordinate system.
The GEOGRAPHY Type: The GEOGRAPHY datatype’s functions are the same as with GEOMETRY. The difference between the two is that when you specify GEOGRAPHY, you are usually specifying points in terms of latitude and longitude.
New Date and Time Datatypes: SQL Server 2008 introduces four new datatypes related to date and time: DATE, TIME, DATETIMEOFFSET, and DATETIME2.
DATE: The new DATE type just stores the date itself. It is based on the Gregorian calendar and handles years from 1 to 9999.
TIME: The new TIME (n) type stores time with a range of 00:00:00.0000000 through 23:59:59.9999999. The precision is allowed with this type. TIME supports seconds down to 100 nanoseconds. The n in TIME (n) defines this level of fractional second precision, from 0 to 7 digits of precision.
The DATETIMEOFFSET Type: DATETIMEOFFSET (n) is the time-zone-aware version of a datetime datatype. The name will appear less odd when you consider what it really is: a date + a time + a time-zone offset. The offset is based on how far behind or ahead you are from Coordinated Universal Time (UTC) time.
The DATETIME2 Type: It is an extension of the datetime type in earlier versions of SQL Server. This new datatype has a date range covering dates from January 1 of year 1 through December 31 of year 9999. This is a definite improvement over the 1753 lower boundary of the datetime datatype. DATETIME2 not only includes the larger date range, but also has a timestamp and the same fractional precision that TIME type provides
12. What are the Advantages of using CTE?

Using CTE improves the readability and makes maintenance of complex queries easy.
The query can be divided into separate, simple, logical building blocks which can be then used to build more complex CTEs until final result set is generated.
CTE can be defined in functions, stored procedures, triggers or even views.
After a CTE is defined, it can be used as a Table or a View and can SELECT, INSERT, UPDATE or DELETE Data.

13. What is CLR?

In SQL Server 2008, SQL Server objects such as user-defined functions can be created using such CLR languages. This CLR language support extends not only to user-defined functions, but also to stored procedures and triggers. You can develop such CLR add-ons to SQL Server using Visual Studio 2008.

14. What are synonyms?

Synonyms give you the ability to provide alternate names for database objects. You can alias object names; for example, using the Employee table as Emp. You can also shorten names. This is especially useful when dealing with three and four part names; for example, shortening server.database.owner.object to object.

15. What is LINQ?

Language Integrated Query (LINQ) adds the ability to query objects using .NET languages. The LINQ to SQL object/relational mapping (O/RM) framework provides the following basic features:

Tools to create classes (usually called entities) mapped to database tables
Compatibility with LINQ’s standard query operations
The DataContext class, with features such as entity record monitoring, automatic SQL statement generation, record concurrency detection, and much more
16. What is Isolation Levels?

Transactions specify an isolation level that defines the degree to which one transaction must be isolated from resource or data modifications made by other transactions. Isolation levels are described in terms of which concurrency side-effects, such as dirty reads or phantom reads, are allowed.

Transaction isolation levels control:
Whether locks are taken when data is read, and what type of locks are requested.
How long the read locks are held.
Whether a read operation referencing rows modified by another transaction:
Blocks until the exclusive lock on the row is freed.
Retrieves the committed version of the row that existed at the time the statement or transaction started.
Reads the uncommitted data modification.
17. What is use of EXCEPT Clause?

EXCEPT clause is similar to MINUS operation in Oracle. The EXCEPT query and MINUS query returns all rows in the first query that are not returned in the second query. Each SQL statement within the EXCEPT query and MINUS query must have the same number of fields in the result sets with similar data types.

18. How would you handle error in SQL SERVER 2008?

SQL Server now supports the use of TRY…CATCH con handling. TRY…CATCH lets us build error handling at the level we need, in the way w to, by setting a region where if any error occurs, it will break out of the region and head to an error handler.

The basic structure is as follows:
BEGIN TRY
stmts..
END TRY
BEGIN CATCH
stmts..
END CATCH

19. What is RAISEERROR?

RaiseError generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY | CATCH construct.

20. How to rebuild Master Database?

Master database is system database and it contains information about running server’s configuration. When SQL Server 2005 is installed it usually creates master, model, msdb, tempdb resource and distribution system database by default. Only Master database is th one which is absolutely must have database. Without Master database SQL Server cannot be started. This is the reason it is extremely important to backup Master database.

To rebuild the Master database, Run Setup.exe, verify, and repair a SQL Server instance, and rebuild the system databases. This procedure is most often used to rebuild the master database for a corrupted installation of SQL Server.

21. What is XML Datatype?

The xml data type lets you store XML documents and fragments in a SQL Server database. An XML fragment is an XML instance that is missing a single top-level element. You can create columns and variables of the xml type and store XML instances in them. The xml data type and associated methods help integrate XML into the relational framework of S Server.

22. What is Data Compression?

In SQL SERVE 2008 Data Compression comes in two flavors:

Row Compression: Row compression changes the format of physical storage of data. It minimize the metadata (column information, length, offsets etc) associated with each record. Numeric data types and fixed length strings are stored in variable-length storage format, just like Varchar.
Page Compression: Page compression allows common data to be shared between rows for a given page. Its uses the following techniques to compress data:
Row compression.
Prefix Compression. For every column in a page duplicate prefixes are identified. These prefixes are saved in compression information headers (CI) which resides after page header. A reference number is assigned to these prefixes and that reference number is replaced where ever those prefixes are being used.
Dictionary Compression: Dictionary compression searches for duplicate values throughout the page and stores them in CI. The main difference between prefix and dictionary compression is that prefix is only restricted to one column while dictionary is applicable to the complete page.
23. What is Catalog Views?

Catalog views return information that is used by the SQL Server Database Engine. Catalog Views are the most general interface to the catalog metadata and provide the most efficient way to obtain, transform, and present customized forms of this information. All user- available catalog metadata is exposed through catalog views.

24. What is PIVOT and UNPIVOT?

A Pivot Table can automatically sort, count, and total the data stored in one table or spreadsheet and create a second table displaying the summarized data. The PIVOT operator turns the values of a specified column into column names, effectively rotating a table.

UNPIVOT table is reverse of PIVOT Table.

25. What is Dirty Read ?

A dirty read occurs when two operations say, read and write occurs together giving the incorrect or unedited data. Suppose, A has changed a row, but has not committed the changes. B reads the uncommitted data but his view of the data may be wrong so that is Dirty Read.

26. What is Aggregate Functions?

Aggregate functions perform a calculation on a set of values and return a single value. Aggregate functions ignore NULL values except COUNT function. HAVING clause is used, along with GROUP BY, for filtering query using aggregate values.

Following functions are aggregate functions.

AVG, MIN CHECKSUM_AGG, SUM, COUNT, STDEV, COUNT_BIG, STDEVP, GROUPING, VAR, MAX. VARP

27. What do you mean by Table Sample?

TABLESAMPLE allows you to extract a sampling of rows from a table in the FROM clause. The rows retrieved are random and they are not in any order. This sampling can be based on a percentage of number of rows. You can use TABLESAMPLE when only a sampling of rows is necessary for the application instead of a full result set.

28. What is the difference between UNION and UNION ALL?

UNION The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
UNION ALL The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.
The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.
29. What is B-Tree?

The database server uses a B-tree structure to organize index information. B-Tree generally has following types of index pages or nodes:

root node: A root node contains node pointers to branch nodes which can be only one.
branch node: A branch node contains pointers to leaf nodes or other branch nodes which can be two or more.
leaf nodes: A leaf node contains index items and orizantal pointers to other leaf nodes which can be many.