Wednesday, 29 April 2015

How to display all days in a month by SQL Server?

How to display all days in a month by SQL Server?

DECLARE @RepMonth as datetime
SET @RepMonth = '04/01/2015';
WITH DayList (DayDate) AS
(
    SELECT @RepMonth
    UNION ALL
    SELECT DATEADD(d, 1, DayDate)
    FROM DayList
    WHERE (DayDate < DATEADD(d, -1, DATEADD(m, 1, @RepMonth)))
)
SELECT *
FROM DayList

SQL Server Triggers

Trigger : A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server. A trigger is really an event handler. SQL Server allows users to create triggers (event handlers) for 3 types of events:

  • DML Event - Occurs when a DML (Data Manipulation Language) statement: INSERT, UPDATE or DELETE, is executed.
  • DDL Event - Occurs when a DDL (Data Definition Language) statement: CREATE, ALTER, or DROP, is executed.
  • Logon Event - Occurs when a user logins to the Server.

There are 3 different types of triggers (event handlers) based on the types of events they are triggered by:

  • DML Trigger - Executes in response to a DML event.
  • DDL Trigger - Executes in response to a DDL event.
  • Logon Trigger - Executes in response to a logon event.

SQL Server NULL

Introduction to NULL :
NULL  :A NULL value is a special value that represents an unknown value. SQL Server supports NULL values with the following features:
  • All data types used for table columns support NULL values. In another word, NULL values can be stored in database tables.
  • Individual table columns may be defined to not allow NULL values. In this case, you can not assign NULL values to those columns.
  • "NULL" is a keyword that represent a NULL value in expressions.
  • NULL values can be used directly in SET (assignment) statements.
  • If NULL values are involved in an arithmetic operation, the result will be a numeric NULL.
  • If NULL values are involved in a string operation, the result will be a string NULL.
  • If NULL values are involved in a datetime operation, the result will be a datetime NULL.
  • If NULL values are involved in a bitwise operation, the result will be a binary NULL.
  • If NULL values are involved in a comparison operation, the result will be a Boolean NULL.
  • If NULL values are involved in a Boolean operation, the result could be TRUE, FALSE, or NULL.
  • To test NULL values, you need to use two special operators, IS NULL and IS NOT NULL.
  • Special functions are available to handle NULL values, like ISNULL(), and NULLIF()

How To Assign NULL Values to Variables or Columns?
The rule for assigning NULL values to variables or table columns is simple: Use keyword "NULL" directly as normal values. Specificly,
  • "NULL" can be used in SET statements to assign NULL values to variables.
  • "NULL" can be used in SET clauses in UPDATE statements.
  • "NULL" can be used in value lists in INSERT statements.
  • "NULL" can be used in parameter lists when calling stored procedures or functions.

Assiging NULL values to variables :

DECLARE @birth_date DATETIME;
SET @birth_date = NULL;
SELECT @birth_date;
GO
--------------
NULL

Assiging NULL values to columns:

UPDATE datson SET notes = NULL;
GO

Assiging NULL values to parameters:

EXEC sp_help NULL;
GO

What Happens If NULL Values Are Involved in Arithmetic Operations?
If NULL values are involved in arithmetic operations, the result will be numeric NULL values.
SELECT 7+NULL;
GO
-----------
NULL

SELECT 10.02*NULL;
GO
-----------
NULL

SELECT 4.988E+10/NULL;
GO
-----------
NULL

What Happens If NULL Values Are Involved in String Operations?
If NULL values are involved in string operations, the result will be string NULL values.
SELECT 'sunil'+NULL;
GO
----------
NULL

SELECT LEN(NULL);
GO
----------
NULL

SELECT REVERSE(NULL);
GO
----------
NULL

What Happens If NULL Values Are Involved in Datetime Operations?
If NULL values are involved in datetime operations, the result will be datetime NULL values.
SELECT GETDATE()+NULL;
GO
-----------
NULL

SELECT DATEDIFF(DAY, GETDATE(), NULL);
GO
-----------
NULL

What Happens If NULL Values Are Involved in Bitwise Operations?
If NULL values are involved in bitwise operations, the result will be binary NULL values.
SELECT 1 | NULL;
GO
-----------
NULL

SELECT 707 & NULL;
GO
-----------
NULL

SELECT ~NULL;
GO
-----------
NULL

What Happens If NULL Values Are Involved in Comparison Operations?
If NULL values are involved in comparison operations, the result will be Boolean NULL values. This behavior is very interesting because you would expect a comparison operation returns only one of the two values: TRUE and FALSE. But SQL Server may return you a third value: NULL.
IF 1>NULL PRINT '1>NULL is returning TRUE'
ELSE PRINT '1>NULL is not returning TRUE'
GO
1>NULL is not returning TRUE

IF NOT 1>NULL PRINT '1>NULL is returning FALSE'
ELSE PRINT '1>NULL is not returning FALSE'
GO
1>NULL is not returning FALSE

Another test proves that "'FYI'=NULL" is not returning TRUE or FALSE. It is returning a third value, NULL
IF 'FYI'=NULL PRINT '''FYI''=NULL returns TRUE'
ELSE PRINT '''FYI''=NULL does not return TRUE'
GO
'FYI'=NULL does not return TRUE

IF NOT 'FYI'=NULL PRINT '''FYI''=NULL returns FALSE'
ELSE PRINT '''FYI''=NULL does not return FALSE'
GO
'FYI'=NULL does not return FALSE

What Happens If NULL Values Are Involved in Boolean Operations?
If NULL values are involved in Boolean operations, the result will vary depending on the operator type. For AND operator, FALSE takes precedence over NULL. The result can be summarized in a table below:
AND     TRUE    FALSE   NULL
TRUE    true    false   null
FALSE   false   false   false
NULL    null    false   null
For OR operator, TRUE takes precedence over NULL. The result can be summarized in a table below:
OR      TRUE    FALSE   NULL
TRUE    true    true    true
FALSE   true    false   null
NULL    true    null    null
The tutorial script below shows you that NULL AND FALSE returns FALSE:
IF 0=NULL AND 0=1 PRINT 'NULL AND FALSE returns TRUE'
ELSE PRINT 'NULL AND FALSE does not returns TRUE'
GO
NULL AND FALSE does not returns TRUE

IF NOT (0=NULL AND 0=1)
  PRINT 'NULL AND FALSE returns FALSE'
ELSE PRINT 'NULL AND FALSE does not returns FALSE'
GO
NULL AND FALSE returns FALSE

How To Replace NULL Values in Expressions using ISNULL()?
NULL values presented in expressions will cause the final results to be NULL. Sometimes, you want NULL values to be replaced with some default values, like 0, '', or 'NULL', so that expressions can be evaluated properly.
SQL Server offers a built-in function called ISNULL() to help you replacing NULL values in expressions:
ISNULL(expression, replacement)
-- Returns "expression", if it is not NULL
-- Returns "replacement", if "expression" is NULL
The tutorial example below shows you how to replace possible NULL values in @middle_initial:
CREATE PROCEDURE welcome
  @first_name VARCHAR(20),
  @middle_initial VARCHAR(1),
  @last_name VARCHAR(20)
AS
  PRINT 'Hello '+@first_name
    + ' '+@middle_initial
    + ' '+@last_name;
  PRINT 'Hello '+@first_name
    + ' '+ISNULL(@middle_initial,'')
    + ' '+@last_name;
GO

EXEC welcome 'John', 'W', 'King';
GO
Hello John W King
Hello John W King

EXEC welcome 'John', NULL, 'King';
GO

Hello John  King

The first PRINT statement in the second test returns a blank line because of NULL value

How To Replace Given Values with NULL using NULLIF()?
Sometime you want to hide certain values by replacing them with NULL values. SQL Server offers you a nice function called NULLIF() to do this:
NULLIF(expression, value)
-- Returns NULL if "expression" equals to value"
-- Returns "expression", otherwise
NULLIF() can be viewed as the reverse function of ISNULL(). The tutorial script below shows you a good example of using NULLIF():
SELECT id, counts FROM fyi_links;
GO
id          counts
----------- -----------
101         NULL
102         8
1101        NULL
202         NULL
2101        NULL
2102        NULL
301         NULL
302         NULL

-- converting NULL to 0
UPDATE fyi_links SET counts=ISNULL(counts,0);
GO
SELECT id, counts FROM fyi_links;
GO
id          counts
----------- -----------
101         0
102         8
1101        0
202         0
2101        0
2102        0
301         0
302         0

-- converting 0 to NULL
UPDATE fyi_links SET counts=NULLIF(counts,0);
GO
SELECT id, counts FROM fyi_links;
GO
id          counts
----------- -----------
101         NULL
102         8
1101        NULL
202         NULL
2101        NULL
2102        NULL
301         NULL

302         NULL

SQL Server Subquery

Subquery: A subquery—also referred to as an inner query or inner select—is a SELECT statement embedded within a data manipulation language (DML) statement or nested within another subquery. You can use subqueries in SELECT, INSERT, UPDATE, and DELETE statements wherever expressions are allowed.

A DML statement that includes a subquery is referred to as the outer query. The following guidelines provide details about how to implement subqueries in your outer queries or in other subqueries:
·         You must enclose a subquery in parenthesis.
·         A subquery must include a SELECT clause and a FROM clause.
·         A subquery can include optional WHERE, GROUP BY, and HAVING clauses.
·         A subquery cannot include COMPUTE or FOR BROWSE clauses.
·         You can include an ORDER BY clause only when a TOP clause is included.
·         You can nest subqueries up to 32 levels.
A subquery is a SQL query nested inside a larger query.

  • A subquery may occur in :
A SELECT clause
A FROM clause
A WHERE clause
  • The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or inside another subquery.
  • A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
  • You can use the comparison operators, such as >, <, or =. The comparison operator can also be a multiple-row operator, such as IN, ANY, or ALL.
  • A subquery can be treated as an inner query, which is a SQL query placed as a part of another query called as outer query.
  • The inner query executes first before its parent query so that the results of inner query can be passed to the outer query.
  • When subqueries are used in a SELECT statement they can only return one value. This should make sense, simply selecting a column returns one value for a row, and we need to follow the same pattern.
  • In general, the subquery is run only once for the entire query, and its result reused. This is because, the query result does not vary for each row returned.
  • It is important to use aliases for the column names to improve readability.

Syntax :

SELECT select_list
FROM Table1
WHERE expr Operator
              (SELECT select_list
                FROM Table1)



  • The subquery (inner query) executes once before the main query (outer query) executes.
  • The main query (outer query) use the subquery result.

Adding Subqueries to the SELECT Clause :
You can add a subquery to a SELECT clause as a column expression in the SELECT list. The subquery must return a scalar (single) value for each row returned by the outer query.
For example, in the following SELECT statement, I use a subquery to define the TotalQuantity column:
SELECT
  SalesOrderNumber,
  SubTotal,
  OrderDate,
  (
    SELECT SUM(OrderQty)
    FROM Sales.SalesOrderDetail
    WHERE SalesOrderID = 2356
  ) AS TotalQuantity
FROM
  Sales.SalesOrderHeader
WHERE
  SalesOrderID = 2356;

Notice I’ve inserted the subquery as the fourth column expression in the SELECT list and named the column TotalQuantity. The subquery itself is enclosed in parentheses and made up of a single SELECT statement. The statement retrieves the total number of items sold for sales order 43659. Because there are multiple line items in this order, I used the SUM aggregate function to add the numbers together and return a single value. The following table shows the result set returned by the outer SELECT statement.

SalesOrderNumber
SubTotal
OrderDate
TotalQuantity
SO43659
24643.9362
2001-07-01 00:00:00.000
26

How to enable mixed authentication in SQL server?

How to enable mixed authentication in SQL server?

On the SQL Server start SQL Server Management Studio.
          

Enter the Server name and select Windows authentication.Make sure you are logged in with administrator credentials.


Right click on the server name and select properties.



Go to Security and select SQL Server and Windows Authentication Mode.


Right click on the server name and select Restart to restart the SQL services.


Now check it and mixed mode will be enabled.



Tuesday, 28 April 2015

How to get date of 5 days back in SQL Server?

How to get date of 5 days back  in SQL Server.?


select dateadd(dd,-5,getdate())

How to get most recently Row inserted in a table?

How to get  most recently Row inserted in a table.?


select top 1 * from table_name order by Column_name desc

How to return XML in SQL Server.?

How to return XML in SQL Server.?


We can use FOR XML statement at the end of the query to return XML data from the SQL Server.
select * from table_name FOR XML auto

There are three modes of returning xml  and they are auto, raw and explicit.

Wednesday, 22 April 2015

How to copy data from one table to another table.?

How to copy data  from one table to another table.?

There are multiple ways to do this.

  1. INSERT INTO SELECT : This method is used when table is already created in the database earlier and data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. 
Syntax :
INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2";

  1. SELECT INTO : This method is used when table is not created earlier and needs to be created when data from one table is to be inserted into newly created table from another table. New table is created with same data types as selected columns.
Syntax :
      SELECT column_name(s)
      INTO newtable
      FROM table1;

Commands for rename a db a table and a column?

Commands for rename a db, a table and a column?

To rename db
sp_renamedb 'oldname' , 'newname'
If someone is using database it will not accept sp_renmaedb. In that case first bring db to single user using sp_dboptions. Use sp_renamedb to rename database. Use sp_dboptions to bring database to multi user mode.
Example :.
USE master;
GO
EXEC sp_dboption AdventureWorks, 'Single User', True
GO
EXEC sp_renamedb 'AdventureWorks', 'AdventureWorks_New'
GO
EXEC sp_dboption AdventureWorks, 'Single User', False

To rename Table
We can change the table name using sp_rename as follows,
sp_rename 'oldTableName', 'newTableName'

Example :
SP_RENAME 'Table_First', 'Table_Last'
GO

To rename Column
The script for renaming any column :
sp_rename 'TableName.[OldcolumnName]', 'NewColumnName', 'Column'

Example :.
sp_RENAME 'Table_First.Name', 'NameChange' , 'COLUMN'

GO

Tuesday, 21 April 2015

Which are new data types introduced in SQL SERVER 2008?

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