Thursday, April 24, 2014

SQL server Tricky questions

Below are some SQL basic but Tricky questions.

1.   SELECT 10
      Out of above Query
      A. Throw Error
      B. 10
      C.  0
      D. 1
2. SELECT $
    Output of Above Query
    A.Throw Error
    B. $
   C.1
   D. 0.00
3. SELECT COUNT(*)
    Output of Above Query
   A. Throw Error
   B. 0
  C. 1
  D. *
4. SELECT COUNT ('8')
 Output of Above Query
 A. Throw Error
 B. 8
C. 0
D.1
5. SELECT 'VASU'+1
   Output of Above Query
   A. Throw Error
   B. 'VASU'
   C.VASU
   D. VASU1
6. SELECT 'VASU'+'1'
   Output of Above Query
   A. Throw Error
   B. 'VASU'
   C.VASU
   D. VASU1
7. SELECT (SELECT 'VASU')
   Output of Above Query
   A. Throw Error
   B. 'VASU'
   C. VASU
    D. VASU1

8. SELECT SELECT 'VASU'
   Output of Above Query
   A. Throw Error
   B. 'VASU'
   C. VASU
    D. VASU1
9. SELECT * FROM 'EMP'
    Output of Above Query
   A.Throw Error
   B. Select all the data from EMP Table
   C.EMP
   D.'EMP'
10. SELECT * FROM EMP, DEPT
      Output of Above Query
     A. Throw Error
     B. Cross join of two Tables
     C. Inner Join of Two Tables
     D.Display only EMP Table Data
11. SELECT COUNT(*) + COUNT(*)
      Output of Above Query
    A.Throw Error
    B. 0
    C. 1
    D.2
12. SELECT 'VASU' FROM EMP
      Output of Above Query
      A. Throw Error
      B. Display one time 'VASU'
      C.Dispaly 'VASU' as many rows in the EMP Table
      D. will select EMP table Data
13. SELECT SUM(1+2*3)
      Output of Above Query
     A. Throw Error
     B. 9
     C. 7
     D. 6
14. SELECT  MAX(1+2*3)
      Output of Above Query
     A. Throw Error
     B.3
     C. 7
     D. 6
15.  SELECT MAX(1,3,4)
       Output of  Above Quey
      A. Throw Error
      B. 1
      C. 3
      D. 4
16.SELECT MAX('VASU')
    Output of Above Query
    A. Throw Error
    B. 1
    C. 2
    D. VASU
17.SELECT  Count(SELECT EMPID FROM EMP)
      Output of Above Query
    A. Throw Error
    B. Will Display Count of EMP Table
    C. 0
   D. 1

ANSWERS:

01. B 02. D 03. C 04.D 
05 A 06.D 07.C 08. A 
09. A10.B 11. D. 12. C 
13.C 14. C 15. A 16. D
17. A

 Interview Questions on Temp Tables

1. Is it possible to create Trigger in TempTable?
     Yes
2. Is it possible to Create Primary key on Temp table?
    Yes
3. Is it Possible to Create Foreign Key on Temp Table.
    NO. Except Foreign Key Constrain, remain all constrains we can create on Temp Table.



Tuesday, October 29, 2013

How to hide null values from the "Drill-Down" Report of SSRS?

one of my colleague asked me this, how to hide null values in the "Drill Down" report of SSRS?

For doing this scenario, i have created the table with below script.


CREATE TABLE Test_Report ( Category Varchar(100), SubCategory Varchar(100) Null, Product Varchar(100) Null, OrderQty int Null, OrderYear int Null)
INSERT INTO Test_Report VALUES
 ( 'Bikes',NULL,NULL,NULL,Null)
,('Bikes',NULL ,NULL,NULL,NULL)
,('Bikes',NULL ,NULL,NULL,NULL)
,('Bikes',NULL ,NULL,NULL,NULL)
,('Bikes',NULL ,NULL,NULL,NULL)
,('Bikes',NULL ,NULL,NULL,NULL)
,('Clothing','ABCDE','EFGHIJ',10,2005)
,('Clothing','ABCDE','EFGHIJ',10,2005)
,('Clothing','ABCDE','EFGHIJ',10,2005)
,('Clothing','ABCDE','EFGHIJ',10,2005)
,('Clothing','ABCDE','EFGHIJ',10,2005)
,('Clothing','ABCDE','EFGHIJ',10,2005)
,('Clothing','ABCDE','EFGHIJ',10,2005)
,('Clothing','ABCDE','EFGHIJ',10,2005)
,('Clothing','ABCDE','EFGHIJ',10,2005)
,('Clothing','ABCDE','EFGHIJ',10,2005)
,('Clothing','ABCDE','EFGHIJ',10,2005)
,('Accessories','ABCDE','pqrst',20,2006)
,('Accessories','ABCDE','pqrst',20,2006)
,('Accessories','ABCDE','pqrst',20,2006)
,('Accessories','ABCDE','pqrst',20,2006)
,('Accessories','ABCDE','pqrst',20,2006)
,('Accessories','ABCDE','pqrst',20,2006)           
,('Accessories','ABCDE','pqrst',20,2006)
,('Accessories','ABCDE','pqrst',20,2006)
,('Accessories','ABCDE','pqrst',20,2006)
,('Accessories','ABCDE','pqrst',20,2006)
,('Accessories','ABCDE','pqrst',20,2006)
,('Components','ZYXW','VUTSRQP',30,2013)
,('Components','ZYXW','VUTSRQP',30,2013)
,('Components','ZYXW','VUTSRQP',30,2013)
,('Components','ZYXW','VUTSRQP',30,2013)
,('Components','ZYXW','VUTSRQP',30,2013)
,('Components','ZYXW','VUTSRQP',30,2013)
,('Components','ZYXW','VUTSRQP',30,2013)
,('Components','ZYXW','VUTSRQP',30,2013)
,('Components','ZYXW','VUTSRQP',30,2013)

Wednesday, August 21, 2013

Working with "CHARACTER MAP" transformation in SSIS

Today i will cover "CHARACTER MAP" Transformation.
In this post i will cover,
  • what is Character mapping?
  • how to use character mapping?
  •  why to use character mapping?
  • what are the types of conversions we can do using "Character Map" transformation?
CHARACTER MAP:
 Character map transformation is one of basic and less use transformation ,present in Data Flow Tool Box.


Character Mapping will convert string format into required format (UPPER CASE, lower case, Full width, Half width..).

Character map transformation look like below in Data Flow Tool Box
 By using character Mapping we can do following operations .

How to use Character Map transformation:
First add "DATA FLOW TASK" in "CONTROL FLOW".
  
 

Then, double click on "Data Flow" Task, Now you are in "Data Flow" Designer Tab.

Drag "Character Map" Transformation from the available transformations into "Data Flow" designer.
 Right click on "Character Map" and select "Edit" to view available operations.

After Clicking "Edit", it shows available columns, from these select  one column to perform operation.




After selecting column, we can  select "New column" or "In-Place Change" under "Destination".





Click on "Operation", it shows list of available operations what we can perform. Here i selected "UPPER CASE" operation ( it converts all case into UPPER CASE)..

Connect this transform to destination or another transform. Here i connected to sort transformation and added "Data viewer" to view the output.
Execute the package. And here is the required output.




Tuesday, August 20, 2013

Difference Between "Contol Flow" and "Data Flow" in SSIS

If you are a beginner for SSIS, you should know the difference between "Control Flow" and "Data Flow".
 First we start with Control Flow
CONTROL FLOW:
 As the name suggest, "Control Flow" means controlling the flow of execution of SSIS package. Before designing the SSIS package, you have to know the flow of containers/tasks.
For ex: you want to design SSIS package with following conditions .
            i. Data has to load to SQL server
           ii. Before loading the data , already present data in the table should be delete.

To design above package, first we have to create "Execute SQL task" then  connect it to " Data flow task" by using "precedence containers" to load the data. i will discuss later about "Precedence Constraints".

Control flow consists of many components like... Execute SQL task, For Each loop Container,Data flow task.. and so on. We need to understand whether we have to connect sequential or parallel.
Below image explains parallel and sequential connections.



 In the above package, "Bulk Insert Task" and "Data Flow Task" execute serially . "Sequence Container" and "For each loop Container" execute simultaneously.

Data Flow task:
 Data flow task is heart of SSIS. Major ETL tasks performed in "Data Flow task" only. As the name suggested, this task is used to transfer the data from Source to destination. While transferring the data, we can use transformations like... conditional split, row sampling, derived column.. etc. The entire process is called... Extracting data from Source , Transforming the data into it desired and Load the data into Destination, which is called ETL . In this "Transformation" is optional.



In the above package
Source: OLEDB Source ( From where we are extracting the data)
Transformation: Performing some operations to get required format
Destination: Flat File (Loading the data into Destination).

Precedence Constraints:
 Precedence constraints used in "Control Flow" task. In Control Flow , if you are executing sequentially,  for connecting each task with other we use precedence constraints . These are 3 types
1. Success (Color: Green) : if task1 executes successfully then go to task2
2. Failure (Color: Red): if task1 fails then go to task3
3. Completion  (Color: Blue): if task1 completes (irrespective of success or failure) go to task4.
Below image will help you to understand better.
Creation of precedence Constraint:
When we add any task in control flow designer from tool box, you have noticed one green arrow coming from that task. To create a precedence constraint , you need to connect this arrow with another task/container. If you want to change the constraint from success (Green) to Failure(Red)/ Completion(Blue), you need to double click on that arrow, then following dialogue box will open.

 You can also perform following in precedence constraints:
  • Writing Constraints
  • Writing Expressions
  • For Multiple constraints, you can select "Logical  AND " or "Logical OR".

Thursday, May 23, 2013

Working With BULKINSERT Task in SSIS 2008

Hi Today i will start discuss with "BULK INSERT" Task.

BULK INSERT Task used to copy the large amount data from text files to SQL Server Tables.
EX: You have one (1) million records of data present in your text (.txt) file and if you want to import into SQL Server Table, the easiest way to achieve this is by using BULK INSERT Task.

You can configure BULK INSERT Task Like Below:

1. Drag and drop BULK INSERT TASK from Toolbox to CONTROL FLOW


2.Double Click on Bulk Insert Task to open task editor  . After Opening your Task should look like this

3. Click on "Connections" from the left side menu and choose your SQL DATABASE and Related TABLE By configuring OLEDB Connection Manger.

4. Select "source file" connection path under "source" option.


5. click on the "options" in the left tab of the editor, and select Starting row(First row). Also specify actions to perform on the destinations table or view when the task inserts the data.

 6. At last run the package and your source(.txt) data will copy into Destination (SQL Server Table).

Bulk Insert task is easy to use and configure. But it has some limitations. They are:

1.It only allows to append the data into  the table  and you cannot perform truncate and
load.
2. Only FaltFile can be used as source and not any other types
3. Only SQL Server Databases Can be used as destination. It doesn't Support any other
Files/RDBS Systems.
4. A  failure in the Bulk insert task doesnot automatically load back sucessfully loaded
batches
5. only members of SYSADMIN fixed server role can run a package that contains Bulk.






Thursday, May 2, 2013

How to Display Current Month VS Previous Month column in Matrix?

Today i will explain how to display (currentmonth- Previous Month ) column in Matrix.
 i Have JAN to DEC column grouping and i want to display currentmonth -Previous Month column out of the group column.
Then
write Below expression
=SUM(iif(Fields!Month.Value = Month(now.Addmonths(- 1)), Fields!Orders.Value, Nothing)) 
- SUM(iif(Fields!Month.Value = now.Month, Fields!Orders.Value, Nothing)) 

Tuesday, March 5, 2013

Powerpivot ribbon in WIndows XP and Windows 7


While working on Powerpivot in different  Versions (WIndows XP(SP3), WIndows 7& 8). I have found one  Major difference on Powerpivot.
The power pivot ribbon is not appearing in windows XP.
 This article explains how to use powerpivot ribbon on windows XP by using windows 7 powerpivot ribbon
The windows XP Powerpivot ribbon Looks like 





 Menu Items that Map to the Home Tab

The following graphic shows how features in the Home tab relate to features in the Windows XP menus and toolbar.


 Menu Items that Map to the Design Tab

The following graphic shows how features in the Design tab relate to features in the Windows XP menus. 




Menu Items that Map to the Linked Tables Tab

The following graphic shows how features in the Linked Tables tab relate to features in the Windows XP 

Thursday, July 26, 2012

Difference between Temporary table and table Variable

Hi,
 Today i discuss with one of the important topic "Difference between Temporary tables and table variables"

Feature wise Difference between Table Variables and Temporary Tables

  • Feature Area :: Scope
    1.Table Variables - Current batch
    2.Temporary Tables - Current session, nested stored procedures.Global: all sessions.
  • Feature Area :: Usage
    1.Table Variables - UDFs, Stored Procedures, Triggers, Batches.
    2.Temporary Tables - Stored Procedures, Triggers, Batches.
  • Feature Area :: Creation
    1.Table Variables - DECLARE statement only.
    2.Temporary Tables - CREATE TABLE statement. SELECT INTO statement.
  • Feature Area :: Table name
    1.Table Variables - Maximum 128 characters.
    2.Temporary Tables - Maximum 116 characters.
  • Feature Area :: Column data types
    1.Table Variables - Can use user-defined data types.Can use XML collections.
    2.Temporary Tables - User-defined data types and XML collections must be in tempdb to use.
  • Feature Area :: Collation
    1.Table Variables - String columns inherit collation from current database.
    2.Temporary Tables - String columns inherit collation from tempdb database.
  • Feature Area :: Indexes
    1.Table Variables - Can only have indexes that are automatically created with PRIMARY KEY & UNIQUE constraints as part of the DECLARE statement.
    2.Temporary Tables - Indexes can be added after the table has been created.
  • Feature Area :: Constraints
    1.Table Variables - PRIMARY KEY, UNIQUE, NULL, CHECK, but they must be incorporated with the creation of the table in the DECLARE statement. FOREIGN KEY not allowed.
    2.Temporary Tables - PRIMARY KEY, UNIQUE, NULL, CHECK. Can be part of the CREATE TABLE statement, or can be added after the table has been created. FOREIGN KEY not allowed.
  • Feature Area :: Post-creation DDL (indexes, columns)
    1.Table Variables - Statements are not allowed.
    2.Temporary Tables - Statements are allowed.
  • Feature Area :: Insert explicit values into identity columns (SET Id IDENTITY_INSERT).
    1.Table Variables - The SET IDENTITY_INSERT statement is not supported.  
    2.Temporary Tables - The SET IDENTITY_INSERT statement is supported.
  • Feature Area :: Data insertion
    1.Table Variables - INSERT statement (SQL 2000: cannot use INSERT/EXEC).
    2.Temporary Tables - INSERT statement, including INSERT/EXEC. SELECT INTO statement.
  • Feature Area :: Truncate table
    1.Table Variables - Not allowed.
    2.Temporary Tables - Allowed.
  • Feature Area :: Destruction
    1.Table Variables -Automatically at the end of the batch.
    2.Temporary Tables - Explicitly with DROP TABLE statement. Automatically when session ends. (Global: also when other sessions have no statements using table.)
  • Feature Area :: Transactions
    1.Table Variables - Last only for length of update against the table variable. Uses less than temporary tables.
    2.Temporary Tables - Last for the length of the transaction. Uses more than table variables.
  • Feature Area :: Stored procedure recompilations
    1.Table Variables - Not applicable.
    2.Temporary Tables - Creating temp table and data inserts cause procedure recompilations.
  • Feature Area :: Rollbacks
    1.Table Variables - Not affected (Data not rolled back).
    2.Temporary Tables - Affected (Data is rolled back).
  • Feature Area :: Statistics
    1.Table Variables - Optimizer cannot create any statistics on columns, so it treats table variable has having 1 record when creating execution plans.
    2.Temporary Tables - Optimizer can create statistics on columns. Uses actual row count for generation execution plan.
  • Feature Area :: Pass to stored procedures
    1.Table Variables - SQL 2008 only, with predefined user-defined table type.
    2.Temporary Tables - Not allowed to pass, but they are still in scope to nested procedures.
  • Feature Area :: Explicitly named objects (indexes, constraints).
    1.Table Variables - Not allowed.
    2.Temporary Tables - Allowed, but be aware of multi-user issues.
  • Feature Area :: Dynamic SQL
    1.Table Variables - Must declare table variable inside the dynamic SQL.
    2.Temporary Tables - Can use temporary tables created prior to calling the dynamic sql.
Temp Tables vs. Table Variables
Table variables can be an excellent alternative to temporary tables. They have less overhead associated with them then temporary tables do. However, they have some major limitations
as listed below. Consider using a table variable when it will contain a small amount of data, it will not be used in complex queries, and it does not need to be referenced in another SP call
or a dynamic statement. Both temporary tables and derived tables are stored in tempdb.
Table variables have the following advantages over temporary tables:
• A table variable behaves like a local variable. It has a well-defined scope. This is the function, stored procedure, or batch that it is declared in.
• Table variables result in fewer recompilations of a stored procedure as compared to temporary tables.
• Transactions involving table variables last only for the duration of an update on the table variable. Therefore, table variables require less locking and logging resources.
Table variables have the following drawbacks as compared to temporary tables:
• Non-clustered indexes cannot be created on table variables, other than the system indexes that are created for a PRIMARY or UNIQUE constraint. That can influence the query
performance when compared to a temporary table with non-clustered indexes.
• Table variables do not maintain statistics like temporary tables can. Statistics cannot be created on table variables through automatic creation or by using the CREATE
STATISTICS statement. Therefore, for complex queries on large tables, the lack of statistics may deter the optimizer from determining the best plan for a query, thus affecting the
performance of that query.
• Queries that modify table variables do not generate parallel query execution plans. Performance can be affected when very large table variables, or table variables in complex
queries, are modified.
• The table definition cannot be changed after the initial DECLARE statement.
• Table variables cannot be used in an INSERT EXEC or SELECT INTO statement.
• CHECK constraints, DEFAULT values, and computed columns in the table type declaration cannot call user-defined functions.
• Since the scope of a table variable is local, you cannot reference a table variable defined in an SP from the following:
o Another SP called from the SP that this variable was defined in o A dynamic query run using EXEC() or SP_EXECUTESQL
Temporary Tables: Local vs. Global
A local temporary table, #table_name, exists only for the duration of a user session or the procedure that created the temporary table. When the user logs off or when the procedure that created the table completes, the local temporary table is lost. Multiple users can't share a local temporary table because it is local to one user session. You also can't grant or revoke permissions on the local temporary table.
A global temporary table, ##table_name, also exists for the duration of a user session or the procedure that created the table. When the last user session that references the table
disconnects, the global temporary table is lost. However, multiple users can access a global temporary table; in fact, all other database users can access it. But you can't grant or revoke
permissions on the global temporary table because it's always available to everyone.
Local and global temporary tables differ in a subtle way. Let's look at what SQL Server Books Online (BOL) says about temporary tables. "Temporary tables are similar to permanent
tables, except temporary tables are stored in tempdb and are deleted automatically when no longer in use. The two types of temporary tables, local and global, differ from each other in their names, their visibility, and their lifetimes." The local table we created in our procedure by using sp_executesql won't be accessible to either the procedure or its child procedures.
Within its execution scope, an spexecutesql system stored procedure creates and drops a local table. By definition, when the spexecutesql procedure ends, the life of the table also ends—hence the need to create a global temporary table.

One Simple Example on follwing criteria
Table variables are Transaction neutral. They are variables and thus aren't bound to a transaction. Temp tables behave same as normal tables and are bound by transactions.
A simple example shows this difference quite nicely:
BEGIN TRAN
declare @var table (id int, data varchar(20) )
create table #temp (id int, data varchar(20) )
insert into @var
select 1, 'data 1' union all
select 2, 'data 2' union all
select 3, 'data 3'
insert into #temp
select 1, 'data 1' union all
select 2, 'data 2' union all
select 3, 'data 3'
select * from #temp
select * from @var
ROLLBACK
select * from @var
if object_id('tempdb..#temp') is null
select '#temp does not exist outside the transaction'
We see that the table variable still exists and has all it's data unlike the temporary table that doesn't exists when the transaction rollbacked.

Table variables don't participate in transactions, logging or locking. This means they're faster.
Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option
You can create a temp table using SELECT INTO, which can be quicker to write and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront.
Both table variables and temp tables are stored in tempdb. This means you should be aware of issues such as COLLATION problems if your database collation is different to your server collation; temp tables and table variables will by default inherit the collation of the server, causing problems if you want to compare data in them with d

Monday, July 23, 2012

Pictures To Help You Restore Your Faith In Humanity - Being a Human!

Don’t miss till the End…..

Always be ready to extend any of your little Support….. Your happiness depends on Your kindness….



Being Human!!

if you never learn the language of gratitude, you will never be on speaking terms with happiness.















A father and mother kissing their dying little girl goodbye. If you are wondering why all the medic people are bowing: in less than an hour, two small children in the next room are able to live thanks to the little girl's kidney and liver.

Wednesday, June 13, 2012

first letter Capital in the string of every word in Reporting Services (Camel case)

Today I found a very good function in reporting services, which  Converts the first letter of every word in string to uppercase.
Either Sql server or Reporting Services does not provide any straight forward way to implement the same, we need to write the any user defined function to make the proper case.

But using "strConv" function we can simply achieve.

Here is the syntax:

=StrConv(Fields!Name.Value, vbProperCase)
                                     or
=StrConv(Fields!Name.Value,3)

Converts the first letter of every word in string to uppercase.

To get more details, click on :
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.strconv.aspx

Wednesday, June 6, 2012

how to Display Group Footer in Last page?

Hi,
Today while working , i got problem that "our client want Group Footer should display only in display". After doing lot of R&D   i found the solution.
For Group footer Write following Hidden/Supress expression :
 =IIF(Last(Fields!Field Name.Value,"GroupName")=Last(Fields!Fields Name.Value,"Dataset Name),False,True)

If you execute, you notice that group summation will appear only last page. this is because of above hidden or suppress expression.

Wednesday, May 16, 2012

Custom Code for Dividing Numbers in SSRS

Hi,

Use this custom code when you perform division of 2 numbers. This is essential as when you to try to divide 2 numbers & if the denominator is 0, during run-time the textbox will show error. Below is the code that you can use for eliminating this :

Custom Code:
Public Function SafeDivide(ByVal Numerator, ByVal Denominator)
If Microsoft.VisualBasic.IsNumeric(Numerator) And Microsoft.VisualBasic.IsNumeric(Denominator) Then
If Denominator = 0 Then
  SafeDivide = 0
Else: SafeDivide = Numerator/Denominator
End If
Else
SafeDivide = "N/A"
End If
End Function








                                                                                                                                                                              
write the code function Name in required field like
 =Code.SafeDivide(Fields!Name1.Value,Fields!Name2.Value)
Now if you see the result, You will get exact result. Problem Solved!!!!!!!!

Monday, May 14, 2012

Page Header need to be changed based on Group and Page Header should be appear if data is processed more than one page

While I am working with Reports today I faced one problem,” Page Header is not displaying dynamically based on group, if data is processed more than one page”.
For this I did some R&D and finally got solution for this
Below is the solution
Step 1:
Custom Code:
Dim lastHeader As String = Nothing
Function GetHeader(ByVal currentfooter As String) As String
If Not currentHeader = Nothing Then
lastHeader = currentHeader
End If
Return lastHeader
End Function

Step 2:
Create a group on which your report needs to be display on Page header and Make it asVisble/Hidden ( Depend upon your requirement)

If it is hidden ,then apply hidden property like below



Step 3:
=Code.GetHeader(ReportItems!Fields.Value)



Now you can see the Result . Report Header will change Dynamically according to group and If group data is More than one page in all pages report header will appear

Friday, May 11, 2012

Different format types of DATE and TIME in SQL SERVER 2008

Hi…
Today i will discuss about the displaying DATETIME in different formats in SQL SERVER 2008
While storing DATE and TIME  sometimes client may ask like(dd-mm-yyyy) format  other than default format(yyyy-mm-dd)  . At that time we can use CONVERT function.
First we start with the conversion options available for sql datetime formats with century (YYYY or CCYY format). Subtracting 100 from the Style (format) number will transform dates without century (YY). For example Style 103 is with century, Style 3 is without century. The default Style values – Style 0 or 100, 9 or 109, 13 or 113, 20 or 120, and 21 or 121 – always return the century (yyyy) format.
– Microsoft SQL Server T-SQL date and datetime formats
– Date time formats – mssql datetime 
– MSSQL getdate returns current system date and time in standard internal format
SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mm AM (or PM)
                                        – Oct  2 2008 11:01AM          
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                  
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02           
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) – dd mon yyyy
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy
SELECT convert(varchar, getdate(), 108) – hh:mm:ss
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)
                                        – Oct  2 2008 11:02:44:013AM   
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) – yyyymmdd
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm
                                        – 02 Oct 2008 11:02:07:577     
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm
                                        – 2008-10-02T10:52:47.513
– SQL create different date styles with t-sql string functions
SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd
SELECT convert(varchar(7), getdate(), 126)                 – yyyy-mm
SELECT right(convert(varchar, getdate(), 106), 8)          – mon yyyy
            Interview Point of view having knowledge up-to here is enough.
If anybody asks how to format datetime with functions then we have to write the follwoing query.
– SQL Server date formatting function – convert datetime to string
————
– SQL datetime functions
– SQL Server date formats
– T-SQL convert dates
– Formatting dates sql server
CREATE FUNCTION dbo.fnFormatDate (@Datetime DATETIME, @FormatMask VARCHAR(32))
RETURNS VARCHAR(32)
AS
BEGIN
    DECLARE @StringDate VARCHAR(32)
    SET @StringDate = @FormatMask
    IF (CHARINDEX (‘YYYY’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘YYYY’,
                         DATENAME(YY, @Datetime))
    IF (CHARINDEX (‘YY’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘YY’,
                         RIGHT(DATENAME(YY, @Datetime),2))
    IF (CHARINDEX (‘Month’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘Month’,
                         DATENAME(MM, @Datetime))
    IF (CHARINDEX (‘MON’,@StringDate COLLATE SQL_Latin1_General_CP1_CS_AS)>0)
       SET @StringDate = REPLACE(@StringDate, ‘MON’,
                         LEFT(UPPER(DATENAME(MM, @Datetime)),3))
    IF (CHARINDEX (‘Mon’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘Mon’,
                                     LEFT(DATENAME(MM, @Datetime),3))
    IF (CHARINDEX (‘MM’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘MM’,
                  RIGHT(’0′+CONVERT(VARCHAR,DATEPART(MM, @Datetime)),2))
    IF (CHARINDEX (‘M’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘M’,
                         CONVERT(VARCHAR,DATEPART(MM, @Datetime)))
    IF (CHARINDEX (‘DD’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘DD’,
                         RIGHT(’0′+DATENAME(DD, @Datetime),2))
    IF (CHARINDEX (‘D’,@StringDate) > 0)
       SET @StringDate = REPLACE(@StringDate, ‘D’,
                                     DATENAME(DD, @Datetime))   
RETURN @StringDate
END
GO

SQL Server Interview Questions

1.   What is DATABASE?
Collection of interrelated data is called database.
Database is two types.
1. Database (On-line Transaction process database) :- running the business
2. DataWareHouse (On –Line Analytical Process Database):- Analyzing the business .
  • Databases are created to keep details about day-to-day transactions.
2.What is DBMS (Database Management System)?
DBMS is a specification set of features.
Any software which implements specifications of DBMS is called DBMS software.
Ex: Sql Server, Oracle
Using DBMS software users can create and manage database.
USER
↓
DBMS Software
↓
Database
                                                                                                                                                                3.Different types of keys in RDBMS?
  • Primary key:-
     Primary key is used to uniquely identify the records.
In the Below table Primary key is “Empid”
EX:
Empid Salary Name
100 2000 A
 101 5000 B
102 4000 C
  • Composite key:-
     If a Combination of uniquely identify the records present in the table, then those combination keys is called “composite key”.


Student ID(SID) Course ID(CID) Student name(SNAME) Course name(CNAME) Date of Completion(DOC)
100 10 A C 26/10
100 11 A C++ 31/11
101 11 B C 26/10
In the Above table SID, CID are called as Combination key
  • Candidate key:-
     Attributes which are eligible for primary keys are called as candidate keys.
Vehicle no Engine no Vehicle Type Price
AP09 2345 12345 NANO 1,00,000
AP09 9988
56789 TAVERA 3,25,000
AP12 7777 12567 SUMO 2,00,000
In the above table Vehicle no and Engine No is called as Candidate keys.
If we take one as primary key (vehicle no), other will automatically considered as Secondary key (Engine No).
A table may contain many candidate keys but only one primary key is present.
A primary key can be candidate key but a candidate key cannot be primary key.
  • Foreign key:-
     Foreign key is used to establish relationship between two tables.
4.What are the versions of Sql Server ?
Sql Server 6.5
Sql Server 7.0
Sql server 8.0(2000)
Sql Server 9.0(2005)
Sql Server 10.0(2008)
5.What are the default databases installed in the server?
Master: The Master database holds information for all databases located on the SQL Server instance and is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care.
Model:-The model is essentially a template database used in the creation of any new user database created in the instance.
MSDb:- 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.
TempDb:- The tempdb holds temporary objects such as global and local temporary tables and stored procedures.
Once the server is closed again Temporary database is again recreated freshly.
6.What is a Query?
Instruction, command, request given to perform some operations.
7.What are the types of Sub languages in SQL SERVER?
Depends on operations performed by user, SQL is categorized into following Sub languages
  1. DDL( Data Definition language)
  2. DML(Data manipulation Language)
  3. DRL(Data Retrieval Language)
  4. TCL(Transaction Control language)
  5. DCL(Data Control Language)
DDL:-
Data definition is also called Metadata
DDL Commands:
          CREATE: To Create Data Definition
          ALTER: To Modify Data Definition
          DROP: - To Delete Data Definition
          TRUNCATE: - Deletes all the data in the table. It makes table as Empty set.
Data definition can exist without data but data never exist without data definition.
DML Commands
          INSERT:- To insert Data/Record
          UPDATE:- To Modify data
          DELETE: – To delete Record(s).
In Sql Server 2008 one more command is introduced.
          MERGE: - It is Combination of insert & Update. It also called as UPSERT.
DRL Commands
          SELECT:- It is used to retrieve data from database
TCL Commands
          COMMIT:- To save Transactions
          ROLLBACK:-To cancel transactions
DCL Commands
          GRANT:- To give the permissions.
          REVOKE:- To Take back the permissions