Sunday 25 November 2012

0 SQL Server 2012 - New Logical Functions

SQL Server 2012 introduces a new category of built-in scalar functions, the logical functions, which as the name implies, performs logical operations.  SQL Server 2012 introduces 2 new scalar functions under this newly created logical function category, namely the CHOOSE function and the IIF function.  The CHOOSE logical function returns the item at the specified index from a list of values while the IIF logical function returns one of two values, depending on whether the Boolean expression evaluates to true or false.


CHOOSE Logical Function
The CHOOSE logical function acts like an index into an array, where the array is composed of the parameters that follow the index parameter. The index parameter determines which of the following values will be returned. Here’s the syntax of the CHOOSE logical function:


CHOOSE ( <index>, <value_1>, <value_2> [, <value_n>] )
The <index> parameter is an integer expression that represents a 1-based index into the list of items following it.  If the provided index value has a numeric data type other than INT, then the value is implicitly converted to an INT data type. If the index value is 0, a negative number or exceeds the bounds of the array of values, then the CHOOSE logical function will return a NULL value.

The <value_1>, <value_2>, <value_n> parameters are a list of values of any data type. From these parameters, which may be of different data types, the CHOOSE function will return the data type with the highest precedence.

Here’s a couple of examples on how the CHOOSE logical function can be used.
SELECT [ContestantName], CHOOSE([Position], '1st Place', '2nd Place', '3rd Place') AS [Placement]
FROM [dbo].[Contestant]

SELECT [PlayerName], CHOOSE([Ranking], 'Gold Medal', 'Silver Medal', 'Bronze Medal') AS [Reward]
FROM [dbo].[Player]

As another example, here’s how to translate a numeric month into the name of the month using the CHOOSE logical function. This same statement can be done using the CASE statement. This can be useful when only the month and year is stored in the database instead of the full date, such as the case of credit card expiration dates:
SELECT [CardHolderName], CHOOSE([ExpirationMonth], 'January', 'February', 'March', 'April', 
'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') + ' ' + 
CAST([ExpirationYear] AS VARCHAR(4)) AS [ExpirationDate]
FROM [dbo].[CreditCard]


IIF Logical Function
The IIF logical function returns one of two values, depending on whether the first parameter of the function, which is a Boolean expression, evaluates to true or false. The syntax for the IIF logical function is as follows:
IIF ( <boolean_expression>, <true_value>, <false_value> )
The <boolean_expression> parameter is any valid Boolean expression.  If this parameter is not a Boolean expression, then a syntax error will be raised. The <true_value> parameter is the value that the IIF logical function will return if the <Boolean_expression> evaluates to true.  On the other hand, the <false_value> parameter is the value that the IIF logical function will return if the <Boolean_expression> evaluates to false or unknown.  The data type of the returned value will be the data type with the highest precedence between the data types in the <true_value> parameter and <false_value> parameter.

Here’s a simple example of the use of the IIF logical function:
SELECT [StudentNumber], IIF( [TestScore] >= 65, 'Pass', 'Fail' ) AS [PassFail]
FROM [dbo].[StudentTest]
Here’s another example but using a nested IIF function:
SELECT [StudentNumber], IIF( [GradePoint] BETWEEN 92 AND 100, 'A',
                        IIF( [GradePoint] BETWEEN 83 AND 91,  'B',
                        IIF( [GradePoint] BETWEEN 74 AND 82,  'C',
                        IIF( [GradePoint] BETWEEN 65 AND 73,  'D',
                        IIF( [GradePoint] < 65, 'F', 'I' ))))) AS [LetterGrade]
FROM [dbo].[Student]
Here’s how the same query will look like using the CASE statement instead of the IIF function:
SELECT [StudentNumber], CASE WHEN [GradePoint] BETWEEN 92 AND 100 THEN 'A'
                             WHEN [GradePoint] BETWEEN 83 AND 91  THEN 'B'
                             WHEN [GradePoint] BETWEEN 74 AND 82  THEN 'C'
                             WHEN [GradePoint] BETWEEN 65 AND 73  THEN 'D'
                             WHEN [GradePoint] < 65 THEN 'F'
                             ELSE 'I' END AS [LetterGrade]
FROM [dbo].[Student]
Source: http://www.sql-server-helper.com/sql-server-2012/sql-server-2012-new-iif-choose-logical-functions.aspx

0 SQL Server 2012 - New String Functions

SQL Server 2012 introduces 2 new string functions, namely the CONCAT string function and the FORMAT string function. The CONCAT string function concatenates two or more string values while the FORMAT string function formats a value with the specified format and optional culture.

CONCAT String Function

The CONCAT string function, which is short for concatenate, returns a string that is the result of concatenating two or more string values.


CONCAT ( <string_value1>, <string_value2> [, <string_valueN> ] )
The input parameters, string_value1, string_value2, string_valueN, are the string values that will be concatenated together in the order specified. All arguments are implicitly converted to string types and then concatenated. NULL values are implicitly converted to an empty string. If all arguments are NULL, an empty string of type VARCHAR(1) is returned. The implicit conversion of strings follows the existing rules for data type conversions.
Prior to SQL Server 2012, to concatenate strings the string concatenation operator used is the plus (+) sign. This string concatenation operator is still valid in SQL Server 2012. There are 2 notable differences between these 2 ways of concatenating strings.

The first difference is in the handling NULL values. Using the + string concatenation operator, if any of the string values being concatenated is NULL and the CONCAT_NULL_YIELDS_NULL setting is set to ON, then the result will be NULL. With the CONCAT string function, regardless of the setting of the CONCAT_NULL_YIELDS_NULL option, all NULL values are implicitly converted to an empty string.

Another notable difference is in concatenating values of different data types. With the CONCAT string function, all non-string data types are implicitly converted to string data type before being concatenated. With the + string concatenation operator, if the values being concatenated are of different data types, the rules of data precedence will convert the data type of the lower precedence to the data type with the higher precedence. If the conversion is not a supported implicit conversion then an error is generated.

FORMAT String Function
The FORMAT string function returns a value formatted with the specified format and optional culture.
FORMAT ( <value>, <format> [, <culture> ] )
The first argument, <value>, is the expression to be formatted. It has to be one of the supported data types, which are either numeric data types (BIGINT, INT, SMALLINT, TINYINT, DECIMAL, NUMERIC, FLOAT, REAL, SMALLMONEY or MONEY) or date and time data types (DATE, TIME, DATETIME, SMALLDATETIME, DATETIME2 or DATETIMEOFFSET).

The second argument, <format>, must contain a valid .NET Framework format string, either as a standard format string, such as 'd' (short date pattern) or ‘F’ (full date/time pattern) for date/time data type format or ‘C’ (currency), ‘N’ (number) or ‘P’ (percent) for numeric data type format, or as a pattern of custom characters for dates and numeric values (for example, 'MM/dd/yyyy hh:mm:ss tt').

Here’s a list of commonly used formats both for date/time data types and numeric data types:
Format SpecifierDescriptionSQL StatementSample Output
Standard Date and Time Format Strings
'd'Short date pattern.FORMAT(SYSDATETIME(),'d')1/24/2012
'D'Long date pattern.FORMAT(SYSDATETIME(),'D')Tuesday, January 24, 2012
'f'Full date/time pattern (short time).FORMAT(SYSDATETIME(),'f')Tuesday, January 24, 2012 2:19 PM
'F'Full date/time pattern (long time).FORMAT(SYSDATETIME(),'F')Tuesday, January 24, 2012 2:19:39 PM
'g'General date/time pattern (short time).FORMAT(SYSDATETIME(),'g')1/24/2012 2:19 PM
'G'General date/time pattern (long time).FORMAT(SYSDATETIME(),'G')1/24/2012 2:19:39 PM
't'Short time pattern.FORMAT(SYSDATETIME(),'t')2:19 PM
'T'Long time pattern.FORMAT(SYSDATETIME(),'T')2:19:39 PM
Standard Numeric Format Strings
'C' or 'c'CurrencyFORMAT(9876.543,'C')
FORMAT(9876.543,'C0')
$9,876.54
$9,877
'D' or 'd'DecimalFORMAT(9876543,'D')
FORMAT(9876543,'D10')
9876543
0009876543
'N' or 'n'NumericFORMAT(9876.543,'N')
FORMAT(9876.543,'N0')
9,876.54
9,877
'P' or 'p'PercentFORMAT(0.98765,'P')
FORMAT(0.98765,'P1')
98.77%
98.8%
The third argument, <culture>, is optional and is used to specify the culture, which is any culture supported by the .NET Framework. If this argument is not provided, then the language of the current session is used.
Here are a few cultures that can be specified on this optional argument:
Culture NameLanguage - Country/Region
en-USEnglish - United States
en-GBEnglish - United Kingdom
fr-FRFrench - France
it-ITItalian - Italy
nl-NLDutch - The Netherlands
de-DEGerman - Germany
pt-BRPortuguese - Brazil
pt-PTPortuguese - Portugal
esSpanish
es-ARSpanish - Argentina



Source: http://www.sql-server-helper.com/sql-server-2012/sql-server-2012-new-string-functions.aspx

0 Uses of the CHARINDEX Function


The CHARINDEX string function returns the starting position of the specified expression in a character string.  It accepts three parameters with the third parameter being optional.
CHARINDEX ( expression1, expression2, [ , start_location ] )
The first parameter is the expression that contains the sequence of characters to be found.  The second parameter is the expression searched for the specified sequence.  This is typically a column from a table.  The third parameter, which is optional, is the character position to start searching expression1 in expression2.
SELECT CHARINDEX('the', 'the quick brown fox jumps over the lazy dog') AS [Location]

Location
----------------
1
SELECT CHARINDEX('the', 'the quick brown fox jumps over the lazy dog', 10) AS [Location] Location ---------------- 32
SELECT CHARINDEX('jumped', 'the quick brown fox jumps over the lazy dog') AS [Location] Location ---------------- 0
One useful use of the CHARINDEX is in getting the first name and last name from a full name:
DECLARE @FullName  VARCHAR(100)
SET @FullName = 'Mickey Mouse'
SELECT LEFT(@FullName, CHARINDEX(' ', @FullName) - 1) AS [FirstName], 
       RIGHT(@FullName, CHARINDEX(' ', REVERSE(@FullName)) - 1) AS [LastName]

First Name  Last Name
----------  ----------
Mickey      Mouse
The CHARINDEX function can also be used to extract the website from a full URL:
DECLARE @URL   VARCHAR(100)
SET @URL = 'http://www.sql-server-helper.com/tips/tip-of-the-day.aspx'
SELECT SUBSTRING(@URL, CHARINDEX('http://', @URL) + 7, CHARINDEX('/', @URL, 8) - 8) AS [Website]

Website
---------------------------
www.sql-server-helper.com
Another use of the CHARINDEX string function, which is not too obvious, is in sorting a result set.  Let’s assume you have a table which contains a U.S. State Code and instead of sorting the result alphabetically based on the U.S. State Code you want it sorted by certain states, like CA, FL, TX, NY in that order.  This can be accomplished using the CHARINDEX string function:
SELECT *
FROM [dbo].[Customers]
ORDER BY CHARINDEX([State], 'CA-FL-TX-NY')
Source: http://www.sql-server-helper.com/tips/tip-of-the-day.aspx?tkey=4a59645b-a5a1-4099-b6d2-959d8644cbed&tkw=uses-of-the-charindex-function

0 How To Use Subqueries In SQL


Introduction
In this article I am going to explain how to use Subqueries in SQL. A select statement known as subquery if it is codded within another SQL statement. Subquery can return a single value or a result set. This result set may contain a single column or more than one column.
There are four way to create subquery  in a SELECT statement.
  • In WHERE Clause
  • In HAVING Clause
  • In FROM Clause
  • In SELECT Clause
Example
select * from mcninvoices
where invoicetotal >
( select avg(invoicetotal) from invoices )
Output  
Clipboard14.jpg
Source : http://www.dotnetheaven.com/article/how-to-use-subqueries-in-sql

0 How To Create UNIQUE Constraint In SQL


Introduction 
If you want unique value in any specific column use UNIQUE constraints. UNIQUE constraints does not allow any duplicate value in specific column and provide unique value.
Both Primary key constraint and unique constraint provide unique value. When you want unique value in any specific column but you are not interested to use primary key use Unique.
Difference between Primary key Constraint and Unique Constraint
  • You can use multiple unique constraints on a table but primary key only one.
  • You can use null value in unique constraint but not in primary key constraint but you can use NULL value only one time in unique constraint.  
A UNIQUE constraint can be referenced by a FOREIGN KEY constraint.
Example of Unique Constraint
In this example emp_panno is unique constraint and we know that pan number of every person is unique.
create table empinfo
(
empid int primary key,
depid int foreign key references depinfo(depid) ,
emp_panno int unique,
name varchar(15),
age int,
city varchar(15),
salary money
)
Source : http://www.dotnetheaven.com/article/how-to-create-unique-constraint-in-sql

Saturday 15 September 2012

0 SQL Server 2012 New Date Functions

SQL Server 2008 introduced 4 new data types associated with the date and time, namely, the DATE, TIME, DATETIME2 and DATETIMEOFFSET data types.  The DATE data types stores only a date value while the TIME data type defines a time of a day without time zone awareness and is based on a 24-hour clock.  The DATETIME2 data type defines a date that is combined with a time of day that is based on a 24-hour clock and has a larger date range, a larger default fractional precision and an optional user-specified precision.  Lastly, the DATETIMEOFFSET data type defines a date that is combined with a time of day that has time zone awareness and is based on a 24-hour clock.

SQL Server 2012, on the other hand, is not introducing any new date and time related data types but is introducing a few new date and time functions that return a date and/or time value from their parts.

Function NameDescriptionSyntaxReturn Data Type
DATEFROMPARTSReturns a DATE value for the specified year, month and day.DATEFROMPARTS( <year>, <month>, <day> )DATE
DATETIME2FROMPARTSReturns a DATETIME2 value for the specified date and time and with the specified precision.DATETIME2FROMPARTS( <year>, <month>, <day>, <hour>, <minute>, <seconds>, <fractions>, <precision> )DATETIME2
DATETIMEFROMPARTSReturns a DATETIME value for the specified date and time.DATETIMEFROMPARTS( <year>, <month>, <day>, <hour>, <minute>, <seconds>, <milliseconds> )DATETIME
DATETIMEOFFSETFROMPARTSReturns a DATETIMEOFFSETvalue for the specified date and time and with the specified offsets and precision.DATETIMEOFFSETFROMPARTS( <year>, <month>, <day>, <hour>, <minute>, <seconds>, <fractions>, <hour_offset>, <minute_offset>, <precision> )DATETIMEOFFSET
SMALLDATETIMEFROMPARTSReturns a SMALLDATETIMEvalue for the specified date and time.SMALLDATETIMEFROMPARTS( <year>, <month>, <day>, <hour>, <minute> )SMALLDATETIME
TIMEFROMPARTSReturns a TIME value for the specified time and with the specified precision.TIMEFROMPARTS( <hour>, <minute>, <seconds>, <fractions>, <precision> )TIME

Parameters / Arguments :

  • <year> - Integer expression specifying a year.
  • <month> - Integer expression specifying a month.
  • <day> - Integer expression specifying a day.
  • <hour> - Integer expression specifying hours.
  • <minute> - Integer expression specifying minutes.
  • <seconds> - Integer expression specifying seconds.
  • <milliseconds> - Integer expression specifying milliseconds.
  • <fractions> - Integer expression specifying fractions.  This parameter depends on the <precision> parameter.  For example, if <precision> is 7, then each fraction represents 100 nanoseconds; if <precision> is 3, then each fraction represents a millisecond.
  • <hour_offset> - Integer expression specifying the hour portion of the time zone offset.
  • <minute_offset> - Integer expression specifying the minute portion of the time zone offset.
  • <precision> - Integer literal specifying the precision of the DATETIME2 value to be returned.
In addition to these date/time functions that returns date and time values from their parts, one other new date/time function is the EOMONTH which returns the last day of the month that contains the specified date, with an optional offset.
Function NameDescriptionSyntaxReturn Data Type
EOMONTHReturns the last day of the month that contains the specified date, with an optional offset.EOMONTH( <start_date> [, <month_to_add>] )Date type of <start_date> or DATETIME2(7)
Parameters / Arguments :
  • <start_date> - Date expression specifying the date for which to return the last day of the month.
  • <month_to_add> - Optional integer expression specifying the number of months to add to <start_date>.


0 SQL Server DATEDIFF() Function


Definition and Usage

The DATEDIFF() function returns the time between two dates.

Syntax

DATEDIFF(datepart,startdate,enddate)
Where startdate and enddate are valid date expressions and datepart can be one of the following:
datepartAbbreviation
yearyy, yyyy
quarterqq, q
monthmm, m
dayofyeardy, y
daydd, d
weekwk, ww
weekdaydw, w
hourhh
minutemi, n
secondss, s
millisecondms
microsecondmcs
nanosecondns


Example

Now we want to get the number of days between two dates.
We use the following SELECT statement:
SELECT DATEDIFF(day,'2008-06-05','2008-08-05') AS DiffDate
Result:
DiffDate
61

Example

Now we want to get the number of days between two dates (notice that the second date is "earlier" than the first date, and will result in a negative number).
We use the following SELECT statement:
SELECT DATEDIFF(day,'2008-08-05','2008-06-05') AS DiffDate
Result:
DiffDate
-61



Source : w3schools.com
 

My MSSQL Search Collections Copyright © 2011 - |- Template created by O Pregador - |- Powered by Blogger Templates