Tuesday, August 9, 2011

Find Duplicate Records

SELECT     tablefield, COUNT(tablefield) AS dup_count
FROM         table
GROUP BY tablefield
HAVING     (COUNT(tablefield) > 1)

Thursday, March 10, 2011

Difference Between COUNT(DISTINCT) vs COUNT(ALL)

SELECT COUNT([FieldName])
FROM [TableName]
GOSELECT COUNT(ALL [FieldName])
FROM [TableName]
GOSELECT COUNT(DISTINCT [FieldName])
FROM [TableName]
GO

Tuesday, March 8, 2011

Date Conversions with Different Formats.


select convert (varchar(20),getdate(),20)
output result
2011-03-08 16:53:04

select convert (varchar(20),getdate(),21)
output result
2011-03-08 17:04:09.

select convert (varchar(20),getdate(),22)
output result
03/08/11  5:04:42 PM

select convert (varchar(20),getdate(),23)
output result
2011-03-08

select convert (varchar(20),getdate(),24)
output result
17:05:51

select convert (varchar(20),getdate(),25)
output result
2011-03-08 17:06:16.

select convert (varchar(20),getdate(),100)
output result
Mar  8 2011  4:54PM

select convert (varchar(20),getdate(),101)
output result
03/08/2011

select convert (varchar(20),getdate(),102)
output result
2011.03.08

select convert (varchar(20),getdate(),103)
output result
08/03/2011

select convert (varchar(20),getdate(),104)
output result
08.03.2011

select convert (varchar(20),getdate(),105)
output result
08-03-2011

select convert (varchar(20),getdate(),106)
output result
08 Mar 2011

select convert (varchar(20),getdate(),107)
output result
Mar 08, 2011

select convert (varchar(20),getdate(),108)
output result
17:00:33

select convert (varchar(20),getdate(),109)
output result
Mar  8 2011  5:01:09

select convert (varchar(20),getdate(),110)
output result
03-08-2011

select convert (varchar(20),getdate(),111)
output result
2011/03/08

select convert (varchar(20),getdate(),112)
output result
20110308

select convert (varchar(20),getdate(),113)
output result
08 Mar 2011 17:03:06

select convert (varchar(20),getdate(),114)
output result
17:03:31:553

Wednesday, February 23, 2011

Show Total in SQL

SELECT distinct(b.fieldname),CONVERT(varchar,SUM(a.fieldname),1) as total
 from tablename a, tablename b
 where  a.fieldname=b.fieldname
 group by b.tablename

Wednesday, February 16, 2011

Insert Record from Temp Table to Actual Table

insert into ActualTableName
Select FiledName from TempTable$
where FieldName NOT IN(select FieldName from ActualTableName)

Monday, February 7, 2011

Previous Month Count in SP

CREATE PROCEDURE [dbo].[SP_NAME]

AS
BEGIN

select FieldName,count(FieldName)as alias from tablename
where fielddate>= DATEADD(month, DATEDIFF(month, 0, getdate()) - 1, 0)
AND dt < DATEADD(month, DATEDIFF(month, 0, getdate()), 0)
group by FieldName
 HAVING COUNT(FieldName) >= 1
 ORDER BY FieldName ASC
END

Thursday, January 20, 2011

Store Procedure with Date Difference and DateTime Conversion

@Parameter int,
@ParameterDateName DateTime,
@ParameterDateName DateTime
SELECT FieldName,FieldName,DATEDIFF(day, FieldDateName, GETDATE()) as abc,FieldName from TableName where DATEDIFF(day, FieldDateName, GETDATE()) > @Parameter
  and
  FieldDateName>= convert(datetime, @ParameterDateName, 20)
  and  FieldDateName <=  convert(datetime, @ParameterDateName, 20) 
 
  ORDER BY Fieldname  desc

Wednesday, January 19, 2011

Store Procedure using Date Difference

CREATE  Proc dbo.ProcedureName  @Parameter datatype

AS
 Begin
  SELECT fieldname,fieldname,DATEDIFF(day, fielddate, GETDATE()) as ABC,fieldname from TableName where DATEDIFF(day, fielddate, GETDATE()) >= @Parameter
 End
GO

Tuesday, January 18, 2011

SQL CURSOR Example

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Store Procedure Name]

AS
BEGIN

DECLARE @tmp TABLE
(
Fieldname varchar(500),
Fieldname varchar(500)
)
Declare @temp_Fieldname varchar(500)
declare @temp_Fieldname varchar(500)
declare @count int

DECLARE PROCEDURE_CURSOR CURSOR FOR
   select Fieldname,Fieldname from Table where DATEDIFF (dd,importdt,GETDATE()) = 0

  OPEN PROCEDURE_CURSOR
  FETCH NEXT FROM PROCEDURE_CURSOR INTO @temp_Fieldname,@temp_Fieldname
  WHILE @@FETCH_STATUS = 0
   BEGIN
    select @count = count(Fieldname) from @tmp where Fieldname = @temp_Fieldname
    if (@count = 0)
     begin
      insert into @tmp values(@temp_Fieldname,@temp_Fieldname)
     end
    else
     begin
      insert into @tmp (Fieldname) values(@temp_Fieldname)
     end
    FETCH NEXT FROM PROCEDURE_CURSOR INTO @temp_Fieldname,@temp_Fieldname
   END


 CLOSE PROCEDURE_CURSOR
 DEALLOCATE PROCEDURE_CURSOR
Select * from @tmp
END

Sunday, January 16, 2011

Biztalk Server Defination


Biztalk is a messaging based integration tool. It consists of several tools like Business Processes (Orchestrations), Business Activity Monitoring (BAM), HAT (Health and Activity Tracking), Rules Engines, BizTalk Server Administrative Console etc.

BizTalk Server 2006 R2 builds upon the Business Process Management and SOA/ESB capabilities and address core challenges found in key vertical industries such as manufacturing and retail. Native capabilities of BTS R2 include support for Electronic Data Interchange (EDI) and AS2 ,Windows Workflow Foundation, WCF as well as RFID.

BizTalk server 2006 R2 application can be created using Visual Studio 2005 provided BizTalk Server SDK is installed into the system. A standard BizTalk Server application consists of Schema, Mapping, and Orchestrations. The heart of the BizTalk Server application is schema that is used to define the message format of source and destination data.

BizTalk Server has capability to talk with any kind of legacy system as it only understand the plain text data (in the form of xml), in order to talk with different systems it has several inbuilt adapter like SQL Adapter, MSMQ Adapter, SMTP Adapter, File Adapter, SOAP Adapter etc.

Saturday, January 15, 2011

SQL Question Answers


What is normalization? Explain different levels of normalization?
Check out the article Q100139 from Microsoft knowledge base and of course, there's much more information available in the net. It'll be a good idea to get a hold of any RDBMS fundamentals text book, especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.
What is denormalization and when would you go for it?
As the name indicates, denormalization is the reverse process of normalization. It's the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.
How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.

It will be a good idea to read up a database designing fundamentals text book.

What's the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a non-clustered index by default. Another major difference is that, primary key doesn't allow Nulls, but unique key allows one NULL only.
What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.

See sp_addtype, sp_droptype in books online.

What is bit datatype and what's the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL. 
Define candidate key, alternate key, composite key.
A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key. 

What are defaults? Is there a column to which a default can't be bound?
A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE DEFUALT in books online.
What is a transaction and what are ACID properties?
A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book.
Explain different isolation levels
An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level.
CREATE INDEX myIndex ON myTable(myColumn)
What type of Index will get created after executing the above statement?
Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise.
What's the maximum size of a row?
8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'. Check out SQL Server books online for the page titled: "Maximum Capacity Specifications".
Explain Active/Active and Active/Passive cluster configurations
Hopefully you have experience setting up cluster servers. But if you don't, at least be familiar with the way clustering works and the two clusterning configurations Active/Active and Active/Passive. SQL Server books online has enough information on this topic and there is a good white paper available on Microsoft site.
Explain the architecture of SQL Server
This is a very important question and you better be able to answer it if consider yourself a DBA. SQL Server books online is the best place to read about SQL Server architecture. Read up the chapter dedicated to SQL Server Architecture.
What is lock escalation?
Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it's dynamically managed by SQL Server.
What's the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.
Explain the storage models of OLAP
Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more infomation.
What are the new features introduced in SQL Server 2000 (or the latest release of SQL Server at the time of your interview)? What changed between the previous version of SQL Server and the current version?
This question is generally asked to see how current is your knowledge. Generally there is a section in the beginning of the books online titled "What's New", which has all such information. Of course, reading just that is not enough, you should have tried those things to better answer the questions. Also check out the section titled "Backward Compatibility" in books online which talks about the changes that have taken place in the new version.
What are constraints? Explain different types of constraints.
Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults.

Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY

For an explanation of these constraints see books online for the pages titled: "Constraints" and "CREATE TABLE", "ALTER TABLE"

What is an index? What are the types of indexes? How many clustered indexes can be created on a table? I create a separate index on each column of a table. what are the advantages and disadvantages of this approach?
Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes. When you craete a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it's row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.

What is RAID and what are different types of RAID configurations?
RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance. MSDN has some information about RAID levels and for detailed information, check out the RAID advisory board's homepage
What are the steps you will take to improve performance of a poor performing query?
This is a very open ended question and there could be a lot of reasons behind the poor performance of a query. But some general issues that you could talk about would be: No indexes, table scans, missing or out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much normalization, excess usage of cursors and temporary tables.

Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000 Performance monitor, Graphical execution plan in Query Analyzer.

Download the white paper on performance tuning SQL Server from Microsoft web site. Don't forget to check out
sql-server-performance.com
What are the steps you will take, if you are tasked with securing an SQL Server?
Again this is another open ended question. Here are some things you could talk about: Preferring NT authentication, using server, databse and application roles to control access to the data, securing the physical database files using NTFS permissions, using an unguessable SA password, restricting physical access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the web server etc.

Read the white paper on SQL Server security from Microsoft website. Also check out
My SQL Server security best practices
What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other's piece. Each process  would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's process.

A livelock is one, where a  request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.

Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks"  in SQL Server books online. Also check out the article Q169960 from Microsoft knowledge base.

What is blocking and how would you troubleshoot it?
Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock type. This forces the second connection to wait, blocked on the first.

Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding efficient transactions.

Explain CREATE DATABASE syntax
Many of us are used to craeting databases from the Enterprise Manager or by just issuing the command: CREATE DATABAE MyDB. But what if you have to create a database with two filegroups, one on drive C and the other on drive D with log on drive E with an initial size of 600 MB and with a growth factor of 15%? That's why being a DBA you should be familiar with the CREATE DATABASE syntax. Check out SQL Server books online for more information.
How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in single user mode and -f is used to start the SQL Server in minimal confuguration mode. Check out SQL Server books online for more parameters and their explanations.
As a part of your job, what are the DBCC commands that you commonly use for database maintenance?
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of DBCC commands which are very useful for DBAs. Check out SQL Server books online for more information.
What are statistics, under what circumstances they go out of date, how do you update them?
Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query.

Some situations under which you should update statistics:
1) If there is significant change in the key values in the index
2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated
3) Database is upgraded from a previous version

Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE, DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats, sp_updatestats

What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.
Explian different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would you go about choosing a backup plan?
Types of backups you can create in SQL Sever 7.0+ are Full database backup, differential database backup, transaction log backup, filegroup backup. Check out the BACKUP and RESTORE commands in SQL Server books online. Be prepared to write the commands in your interview. Books online also has information on detailed backup/restore architecture and when one should go for a particular kind of backup.
What is database replicaion? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios:
  • Snapshot replication
  • Transactional replication (with immediate updating subscribers, with queued updating subscribers)
  • Merge replication
See SQL Server books online for indepth coverage on replication. Be prepared to explain how different replication agents function, what are the main system tables used in replication etc.
How to determine the service pack currently installed on SQL Server?
The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed. To know more about this process visit SQL Server service packs and versions.
What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?
Cursors allow row-by-row prcessing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors. Here is an example:

If you have to give a flat hike to your employees using the following criteria:

Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine each employee's salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END

Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don't have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing, check out the 'My code library' section of my site or search for WHILE.
Write down the general syntax for a SELECT statements covering all the options.
Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]

What is a join and explain different types of joins.
Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".

Can you have a nested transaction?
Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT
What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement. See books online to learn how to create extended stored procedures and how to add them to SQL Server.

Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-SQL, see '
My code library' section of this site.
What is the system function to get the current user's user id?
USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().
What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?
Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.

In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple triggers per each action. But in 7.0 there's no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder

Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers.

Also check out books online for 'inserted table', 'deleted table' and COLUMNS_UPDATED()

There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this implementation? Can this be implemented better?
Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This scenario can be better implemented by logging all the necessary data into a separate table, and have a job which periodically checks this table and does the needful.
What is a self join? Explain it with an example.
Self join is just like any other join, except that two instances of the same table will be joined in the query. Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.

CREATE TABLE emp
(
empid int,
mgrid int,
empname char(10)
)

INSERT emp SELECT 1,2,'Vyas'
INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]
FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]
FROM emp t1
LEFT OUTER JOIN
emp t2
ON
t1.mgrid = t2.empid
 
Given an employee table, how would you find out the second highest salary?

How to Send EMAIL in VB 6.0

=============== FORM ==============================
Private Sub Command1_Click()
Dim RetVal As Boolean
Dim i As Long

' In a real application we'd check the return values to ensure all was well
' Start a session
RetVal = AlterMailSession(Me, StartSession)

' Send a message with multiple addresses and attachments
RetVal = CreateMailMessage(Me, "Test Message 1", " " & Chr(13) & "Test Contents" & Chr(13) & "More stuff")
RetVal = MailMessageTo(Me, "elliot spencer", Primary)
RetVal = MailMessageTo(Me, "elliot spencer", CC)
RetVal = MailMessageTo(Me, "elliot spencer", Primary)
RetVal = MailMessageTo(Me, "elliot spencer", CC)
RetVal = MailMessageTo(Me, "elliot spencer", BlindCC)
RetVal = AddAttachment(Me, "pq.doc", "c:\pq.doc", DataFile)
RetVal = AddAttachment(Me, "pq.doc", "c:\pq.doc", OLEStatic)
RetVal = SendMailMessage(Me)

' Abort this message
RetVal = CreateMailMessage(Me, "Test Message 2", "Test Contents" & Chr(13) & "More stuff")
RetVal = MailMessageTo(Me, "elliot spencer", CC)
RetVal = AbortMailMessage(Me)

' Save this message
RetVal = CreateMailMessage(Me, "Test Message 3", "Test Contents" & Chr(13) & "More stuff")
RetVal = MailMessageTo(Me, "elliot spencer", Primary)
RetVal = SaveMailMessage(Me)

' Stop the current session
RetVal = AlterMailSession(Me, StopSession)
End Sub
================== MODULE ==========================================

'
' Created by E.Spencer - This code is public domain.
'
Private Declare Function RegOpenKey Lib "AdvAPI32.dll" Alias "RegOpenKeyA" (ByVal hKey As Long, _
ByVal lpSubKey As String, phkResult As Long) As Long
Private Declare Function RegQueryValueEx Lib "AdvAPI32.dll" Alias "RegQueryValueExA" (ByVal hKey As Long, _
ByVal lpValueName As String, ByVal lpReserved As Long, lpType As Long, ByVal lpData As String, _
lpcbData As Long) As Long
Private Declare Function RegCloseKey Lib "AdvAPI32.dll" (ByVal hKey As Long) As Long
Private Const HKEY_CURRENT_USER = &H80000001
Public Enum SessMode
   StartSession
   StopSession
End Enum
Public Enum AddrType
   Primary
   CC
   BlindCC
End Enum
Public Enum AttachType
   DataFile
   OLEEmbedded
   OLEStatic
End Enum
Public SStatus, MStatus As String

' Call this function to start and stop MAPI sessions
' Example :- MyBool = AlterMailSession(Me, StartSession)
' MyBool = AlterMailSession(Me, StopSession)
' MyBool will be true if operation succeeded
' First parameter is reference to form that contains MAPI message / session controls
' Second parameter is the required session mode - stop or start.
Public Function AlterMailSession(ByRef FName As Form, Mode As SessMode) As Boolean
AlterMailSession = True
On Error GoTo SessError
If Mode = StartSession Then
   ' Get the default exchange profile name
   FName.MAPISession1.UserName = ReadRegistry(HKEY_CURRENT_USER, _
      "Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\", "DefaultProfile")
   ' If session is already open return immediately
   If SStatus = "Open" Then Exit Function
   ' Set up profile - Default for exchange
   FName.MAPISession1.UserName = "MS Exchange Settings"
   FName.MAPISession1.SignOn ' Start mail session
   FName.MAPIMessages1.SessionID = FName.MAPISession1.SessionID ' Allocate session ID to Mail holder
   SStatus = "Open"
   MStatus = "Ready"
ElseIf Mode = StopSession Then
   ' If session is already closed return immediately
   If SStatus = "Closed" Then Exit Function
   FName.MAPISession1.SignOff ' End mail session
   FName.MAPIMessages1.SessionID = 0
   SStatus = "Closed"
   MStatus = "NotReady"
End If
Exit Function
SessError:
SStatus = "Closed"
MStatus = "NotReady"
AlterMailSession = False
End Function

' Call this function to start a new mail message
' Example :- MyBool = CreateMailMessage(Me, "Test Message", "Test Contents")
' MyBool will be true if operation succeeded
' First parameter is reference to form that contains MAPI message / session controls
' The second parameter is the message subject line.
' The third parameter is the message content text (embed Chr(13) for newlines)
Public Function
CreateMailMessage(ByRef FName As Form, Subject As String, Contents As String) As Boolean
CreateMailMessage = False
' If session is not open return immediately
If SStatus <> "Open" Then Exit Function
CreateMailMessage = True
On Error GoTo MessError
FName.MAPIMessages1.Compose ' Start new message composition
FName.MAPIMessages1.MsgSubject = Subject ' Insert message subject line
FName.MAPIMessages1.MsgNoteText = Contents & Chr(13) & " " ' Insert message text
MStatus = "Open"
Exit Function
MessError:
MStatus = "NotReady"
CreateMailMessage = False
End Function

' Call this function to abort a mail message
' Example :- MyBool = AbortMailMessage(Me)
' MyBool will be true if operation succeeded
' First parameter is reference to form that contains MAPI message / session controls
Public Function AbortMailMessage(ByRef FName As Form) As Boolean
AbortMailMessage = False
' If session is not open return immediately
If SStatus <> "Open" Then Exit Function
' If no current mail message then return immediately
If MStatus <> "Open" Then Exit Function
AbortMailMessage = True
On Error GoTo MessError
FName.MAPIMessages1.Delete (mapMessageDelete)
MStatus = "Ready"
Exit Function
MessError:
AbortMailMessage = False
End Function

' Call this function to send a complete mail message
' Example :- MyBool = SendMailMessage(Me)
' MyBool will be true if operation succeeded
' First parameter is reference to form that contains MAPI message / session controls
Public Function SendMailMessage(ByRef FName As Form) As Boolean
Dim Tries As Integer
SendMailMessage = False
' If session is not open return immediately
If SStatus <> "Open" Then Exit Function
' If no current mail message then return immediately
If MStatus <> "Open" Then Exit Function
SendMailMessage = True
On Error GoTo MessError
Retry:
FName.MAPIMessages1.Send
MStatus = "Ready"
Exit Function
MessError:
Tries = Tries + 1
If Tries < 10 Then GoTo Retry
SendMailMessage = False
End Function

' Call this function to save a complete mail message without sending it
' Example :- MyBool = SaveMailMessage(Me)
' MyBool will be true if operation succeeded
' First parameter is reference to form that contains MAPI message / session controls
Public Function SaveMailMessage(ByRef FName As Form) As Boolean
SaveMailMessage = False
' If session is not open return immediately
If SStatus <> "Open" Then Exit Function
' If no current mail message then return immediately
If MStatus <> "Open" Then Exit Function
SaveMailMessage = True
On Error GoTo MessError
FName.MAPIMessages1.Save
MStatus = "Ready"
Exit Function
MessError:
SaveMailMessage = False
End Function

' Call this function to address a mail message to a recipient
' Example :- MyBool = MailMessageTo(Me, "elliot spencer", Primary)
' MyBool will be true if operation succeeded. Supply display names from address book
' list - names will be resolved to addresses in the address book before being added to
' recipient list.
' First parameter is reference to form that contains MAPI message / session controls
' Second parameter is name of recipient (as displayed in address list)
' Third parameter is type of recipient
Public Function MailMessageTo(ByRef FName As Form, ToName As String, AddrMode As AddrType) As Boolean
MailMessageTo = False
' If session is not open return immediately
If SStatus <> "Open" Then Exit Function
' If no current mail message then return immediately
If MStatus <> "Open" Then Exit Function
MailMessageTo = True
On Error GoTo MessError
FName.MAPIMessages1.RecipIndex = FName.MAPIMessages1.RecipCount ' Update count of recipients
If AddrMode = Primary Then FName.MAPIMessages1.RecipType = 1 ' Set to primary recipient type
If AddrMode = CC Then FName.MAPIMessages1.RecipType = 2 ' Set to carbon copy type
If AddrMode = BlindCC Then FName.MAPIMessages1.RecipType = 3 ' Set to blind carbon copy type
FName.MAPIMessages1.RecipDisplayName = ToName ' Display name as provided
FName.MAPIMessages1.ResolveName ' Resolve display name to real address via address book
Exit Function
MessError:
MailMessageTo = False
End Function

' Call this function to address a mail message to a recipient
' Example :- MyBool = AddAttachment(Me, "Test File", "c:\test.txt", DataFile)
' MyBool will be true if operation succeeded.
' First parameter is reference to form that contains MAPI message / session controls
' Second parameter is name of recipient (as displayed in address list)
' Third parameter is type of recipient
Public Function AddAttachment(ByRef FName As Form, AName As String, APath As String, AttMode As AttachType) As Boolean
AddAttachment = False
' If session is not open return immediately
If SStatus <> "Open" Then Exit Function
' If no current mail message then return immediately
If MStatus <> "Open" Then Exit Function
AddAttachment = True
On Error GoTo MessError
FName.MAPIMessages1.AttachmentIndex = FName.MAPIMessages1.AttachmentCount ' Update count of attachments
If AttMode = DataFile Then FName.MAPIMessages1.AttachmentType = 0
If AttMode = OLEEmbedded Then FName.MAPIMessages1.AttachmentType = 1
If AttMode = OLEStatic Then FName.MAPIMessages1.AttachmentType = 2
FName.MAPIMessages1.AttachmentPosition = FName.MAPIMessages1.AttachmentIndex
FName.MAPIMessages1.AttachmentPathName = APath ' File or object path as provided
FName.MAPIMessages1.AttachmentName = AName ' File or object name as provided
Exit Function
MessError:
AddAttachment = False
End Function

' From my registry read module - just to get the default
' exchange user name (profile name)
'
Public Function ReadRegistry(ByVal Group As Long, ByVal Section As String, ByVal Key As String) As String
Dim lResult As Long, lKeyValue As Long, lDataTypeValue As Long, lValueLength As Long, sValue As String
On Error Resume Next
lResult = RegOpenKey(Group, Section, lKeyValue)
sValue = Space$(2048)
lValueLength = Len(sValue)
lResult = RegQueryValueEx(lKeyValue, Key, 0&, lDataTypeValue, sValue, lValueLength)
If (lResult = 0) And (Err.Number = 0) Then
   sValue = Left$(sValue, lValueLength - 1)
Else
   sValue = "Not Found"
End If
lResult = RegCloseKey(lKeyValue)
ReadRegistry = sValue
End Function

Crystal Report Questions

1 Is it possible to join more than one universe in Business Objects BOE XI? If its so Please explain how is that possible?
Yes, we can join more than one universe in BO we can join 2 master or kernel universes to one derived universe. To Link the universes go to universe parameters->links tab->add link.
2 How many .rpt files are be there in a main report having 2
sub reports? We can keep, one .rpt file for both or we can individually
create .rpt files and made them as single with sub report.[there are 3 .rpt files including the main and 2 sub report. but when the sub reports are inserted into main it will behave like one only.]
3 How to Filter the Crystal reports?
To filter the reports we have to use ?Formulas?.We can prepare the formulas with
(1) Field Explorer (Window) or (2) Writing the code
Syntax for preparing the formulas:
{classname.FieldName} & value. For Ex:
?{Employee.Emp_id}=? + value
?{Employee.Emp_name}=? + value + ??? (Strings to be in single quotes)
4 How to present data from Crystal Reports on to form?
Drag Crystal Report viewer control from toolbox to form.Properties:Crystal Report Name: CRV1
Report Source= or
And call show () method
DOCK=Fill (The control resizes while form is resized [Using Crystalviewer]
5 Is there any feature like summing total in crystal report?
Yes, we can add any database field afterwards also. Select
‘Database Field’ in Insert menu item.
6 Can we use stored procedure for creating the report?
Can. By Adding Command in Crystal Report XI.
7 Does Crystal Report support all the functions that we have
in Oracle?
No, Crystal report does not support all the functions. Like Decode function is there in SQL but not there is crystal report. You need to convert that in crystal report format (in if and else etc.).
8 Can we add any database field once we have chosen ?Close?
button?
Yes, we can add any database field afterwards also. Select
Database Field in Insert menu item.
9 What are the sections that we have in Crystal reports?
1. report header 2. report footer 3. page header 4. page footer 5. details
10 Are there any limitations in crystal reports?
1. In export- While exporting data formatting is lost.
2. If database is having field whose length is more than 255 characters, then you cannot make formula using that field.
3.When you browse data just by right clicking on the field then it displays that is there in the database not the data selected by the query.
[Yes , 1)It will not recognize the HTML tag .This is giving a problem in order to get a bullet indent for some text display in PDF reports.
2) Its not possible to customize the length and width of the legend of a chart.
3) Table object is not given in crystal report. Because of this if we cannot have a table auto grow option as we find it in the MS word table.]
[Limit of tables I have near about 13000+ tables which are created at runtime. I cannot select these tables I think there is a limit near about 8500]
[Crystal doesn't support an LDAP connection.]
[1) You cannot change the format of the date field used in parameter
2) You cannot insert sub report into another sub report
3) You cannot export the report to PDF with group ( it is introduced in Crystal Reports 11 R2)
4) There is no option to save the report in previous versions]
11 Can we use our own SQL for creating a report?
We can also make our own query using Crystal SQL Designer tool provided by SQL. Here you can insert your SQL statement as such. It will save this file as query . And when you create a report instead of using Database button
use Crystal SQL Statement button. [Yes, Using Crystal SQL writer]
12 Can we export data of reports into other format like in world doc etc? yes ..u can, not only in word but also in several formats like pdf, excel. .etc. .u can go to file in the menu in that u have this option
[Reports can be exported to a number of formats, such as spreadsheet, word processor, HTML, ODBC, and common data interchange formats.
Go to File->Export. There are two sub menus, Export Report, Report Export Options. This can be achievable through coding.
ExportDestinationType eExportDestinationType =
ExportDestinationType.DiskFile;
ExportFormatType eExportFormatType =
ExportFormatType.PortableDocFormat;
ExportOptions eExportOptions =
ExportOptions.CreateDiskFileDestinationOptions;]
[Sure.We can save the crystal report as many formats.There are Doc ,xsl, .pdf and etc. The sample code i used in my project is given below.
case "pdf": {
//setting disk file name
crDiskFileDestinationOptions.DiskFileName =
ExportPath + filename;
//setting destination type in our case
disk file
crExportOptions.DestinationOptions =
crDiskFileDestinationOptions;
//setting export format type
crExportOptions.ExportDestinationType =
ExportDestinationType.DiskFile;
//setting previously defined
destination opions to our input report document
crExportOptions.ExportFormatType =
ExportFormatType.PortableDocFormat;
break; }
case "xls": {
//setting disk file name
crDiskFileDestinationOptions.DiskFileName =
ExportPath + filename;
//setting destination type in our case
disk file
crExportOptions.ExportDestinationType =
ExportDestinationType.DiskFile;
//setting export format type
crExportOptions.ExportFormatType =
ExportFormatType.Excel;
//setting previously defined
destination opions to our input report document
crExportOptions.DestinationOptions =
crDiskFileDestinationOptions;
break; }]
13 Can we create report using more than one database?
Yes. We can create report using more than one database like Oracle, Access. Create data source name for both the databases. Select tables from them and create the report. Only restriction is if you use two databases then you cannot see the SQL generated by crystal reports.
14 How do we format field?
Right click on that field and choose format field.
15 How do we connect to the database?
1. Use crystal report built in query.
2. Use the tool Crystal SQL Designer provided by crystal report.
[Most data sources can be chosen through the Database Expert dialog box. The Database Expert appears when you create a report from scratch using Blank Report, or when you choose Database Expert from the Database menu. Note: You also select a data source in the Report Creation Wizards. The Data screen in all of the Report Creation Wizards, except the OLAP Report Creation Wizard, is much like the Database Expert dialog box.
To select a data source Choose Database Expert from the Database menu.
The Database Expert dialog box appears. Use the tree view in the Available Data Sources list of the Data screen to select your data source: Current Connections Favorites History Create New Connection Repository Some popular choices in the Create New Connection folder are described here:
Access/Excel (DAO), Database Files, ODBC (RDO), OLAP OLE DB (ADO)
Note: The data source options available in the Create New Connections folder depend on the data access components selected during installation.]
16 Can we use Crystal report as a stand-alone application?
We can make crystal report stand-alone application also. But for that limitation is for viewing the report user should have crystal reports installed
17 How to "Print" in Crystal Reports while using ASP DOT NET
Platform?
using Crystal Decisions. Shared
CrystalReport1 cr= new CrystalReport1;
'here crystalreport1 is crystal report which we design.
CrystalViewer1.ReportSource = cr;
OR we can directly print the report without showing report
CrystalReport1 cr= new CrystalReport1;
cr.PrintToPrinter(1,False,1,1);
18 What are the advantages or disadvantages of using Crystal
Reports in a Windows Forms application as opposed to say rolling our own reports as HTML and displaying them in the Internet Explorer control?
Advantages (1) Secure as End user cannot modify the data which is appear in the report if we use crystal report to show the report but in HTML, user can modify the report data (2) Report layout is not transparent, so that end user will not know about how we design the report. But in HTML, anybody can study the report layout and can copy the technology (3) Can export into different format like PDF, HTML, XML, etc, and many more...
Disadvantages (1) End user need to have the crystal report viewer in his PC in order to see the crystal report output. But this can be overcome if you export the report as PDF/HTML (2) You need to buy Crystal Report license for each pc you are used to design the crystal report.(3) Must buy the version which allows you to install run time components in end user PC (4) Crystal Report is slow as compare to Active Reports (5) If we have 100 pages report then crystal will need to process all pages and then it shows the output. and many more...
19 What are Crystal Reports and Crystal Reports Explorer?
With Crystal reports explorer one can quickly create and modify reports on the web, and since its built on the trusted Business object enterprise platform, it can easily manage massive user loads, individual access, and application customization.
20 How to conditionally suppress a field based on whether a page number is odd or even?
Select the fieldClick FORMATClick FORMAT FIELDSelect the COMMON tabClick the FORMULA BUTTON to the right of SUPPRESS
(Don't click the suppress check box)
To suppress a field on odd numbered pages
PageNumber MOD 2 = 1
To suppress a field on even numebred pages
PageNumber MOD 2 = 0 Click SAVE IconClose the formula editorClick OK on the FORMAT screen
21 How to pass stored Procedure Parameters to the report?
Choose FileOptions menu. In the Options dialog box Click the Database tab and ensure that Stored Procedures is selected. Selecting "Stored Procedures" automatically displays any available stored procedures when you log on to an SQL database.Click OK to exit the Options dialog box. On the Start Page, click Blank Report.Locate and select the SQL Server data source that contains the stored procedure you want to use.Click Next to go to the Connection Information dialog boxEnter the required information to log in.Click FinishHighlight an SQL stored procedure in the Stored Procedures folder, and click thearrow to add it to the Selected Tables list.
The Enter Parameter Values dialog box appears.Highlight a parameter in the Parameter Fields listAssign a value by typing into the Discrete Value box and then click OKYou are returned to the Database ExpertClick OK and create your report using the fields in the stored procedure.
22 What is the "refresh" button suppose to do on the crystal
Report viewer?
(1). When you use? Refresh? Button in crystal report viewer, it refreshes the report data. (2).When you refresh data from the Preview tab, the Refresh Report Data dialog box appearsSelect the "Use current parameter values" option to use the current parameter value, Select the "Prompt for new parameter values" optionto enter a new parameter value. When you select this option and click OK, the Enter Prompt Values dialog box appears. The program now runs the report using the new value(s) you specified.
23 Is there a way to export a report definition without writing code?
Yes. The following steps work assuming you have Crystal Reports on the machine and the appropriate export dlls loaded.
Open the reportPreview itClick the EXPORT envelopeSelect REPORT DEFINITION for the formatSelect DISK FILEClick OKEnter a file name or accept the defaultClick SAVE. The file is a text file and can be viewed with NOTEPAD.
24 Where is the "save data with report" option?
You can find File menu.
25 Is there a way to export the report formulas, like totals to excel?
Yeah we can do that using crystal report
26 What does it mean when we get the error message "Invalid report version" when try to open a Crystal Report?
Crystal in its evolution has changed the report file format several times. In most cases the file format is FORWARD-compatible. By this I mean a file created in Crystal 6 can be opened in Crystal 6 or higher. When the file format changes were major the format is not BACKWARD compatible. By this I mean a file created in CR 9 cannot be opened in CR 8 or before. Crystal changed the report file format with CR 8 and CR 9. The CR 9 change was because of the introduction of Unicode support. CR 8 has the ability to save a file in CR 7 format. Because of the support for Unicode CR 9, 10, and XI cannot save the file in previous formats.
27 How to write a formula to change a font based upon data?
Select the fieldClick FORMATClick FORMAT FIELDSelect the FONT tabClick the FORMULA BUTTON to the right of FONT
if ({YourField} = Value) then
"Arial"
else
"Times New Roman"
Click SAVE IconClose the formula editorClick OK on the FORMAT screen
28 How to refresh the crystal report from the application?
calling crystalreportcontrolname.reset (by selecting Report menu under Refresh the report menu item at design time) will refresh the report
[crystalreport1.DiscardSavedData=True]
29 How many sub-reports can report can have? 0-256
30 How many sections are there in the report
Header, Detail, Footer and Page Header, Report Header, Page Footer, Report Footer [There are several sections. 1)Report header, 2)Page header, 3)Group header, 4)Detail section, 5)Report footer, 6)Page footer And also we can create our own sections if necessary.]
(collected from http://www.sourcecodesworld.com/faqs/crystal-reports-faq.asp)
31. What is Crystal Report?
Ans: Crystal report is a report generation tool. Generally have interface with VB6. Crystal report basically generates dynamic data. You can format the data in whichever way you feel like.
32. Can we use Crystal report as a stand-alone application?
Ans: Generally we use Crystal Reports with VB6. However we can make crystal report stand-alone application also. But for that limitation is for viewing the report user should have crystal reports installed on his/her PC.
33. How do we connect to the database?
Ans: There are two ways of creating the report: -
1. Use crystal report built in query.
2. Use the tool ‘ Crystal SQL Designer’ provided by crystal report.
When you create report using crystal report built in query then it asks for the data source name that you have created. When you run the report, then for the first time it will ask for the user id and password. After that it will store the same.
When you create ‘.qry’ using ‘Crystal SQL’ Designer then at that time it will ask for the user id and password. When you run the report for the first time instead of asking for the user id and password it will ask for the ‘.qry’ file location. You can change the query location also. For that open the report, select ‘Set Location’ option in Database menu item, and set the location.
34. How do we format field?
Ans: For formatting any field just right click on it and you will get many options like ‘Format Field.’ ‘Browse field data’ etc. Click on ‘Format Field.’ You can align data, suppress, make it multiline, change the font size, style, and type, make it hyperlink etc.
If it is an amount field then you can display currency symbol also. Right click on the field select ‘Format Field’.
35. Can we give parameters to the report?
Ans: We can very well give parameters to the report. For creating parameters select ‘Parameter Field’ in Insert menu item. ‘Create Parameter Field’ dialog box will popped up, it will ask for the name of parameter, prompting text and datatype. Now when you run the report it will prompt for these parameters.
36.Can we create our own formulas in reports?
Ans: We can create our own formulas in reports. Select ‘Formula Field’ in Insert menu item. Write the formula in ‘Formula Editor’. Here you will get ‘Field Tree’, ‘Function Tree’, and ‘Operator Tree’, which will display the report fields, functions that are supported by crystal reports (like CDATE () etc.), operators (arithmetic, strings etc.) respectively.
37. Can we create report using more than one database?
Ans: We can create report using more than one database like Oracle, Access. Create data source name for both the databases. Select tables from them and create the report.
Only restriction is if you use two databases then you cannot see the SQL generated by crystal reports.
38. Can we export data of reports into other format like in world doc etc?
Ans: Generated data can be exported to word doc, or in rich text format. Just click on ‘Export’ icon in the menu. Export dialog box will be popped up. It will ask for the ‘Format’ like comma-separated value (csv) etc and the ‘Destination’ like disk, application etc. After that it will ask for the file name and save the data.
Only restriction is formatting of data will be lost, but crystal report will try to maintain as much formatting as it can.
39. Can we use our own SQL for creating a report?
Ans: We can also make our own query using ‘Crystal SQL Designer’ tool provided by SQL. Here you can insert your SQL statement as such. It will save this file as ‘.qry’ . And when you create a report instead of using ‘Database’ button use ‘Crystal SQL Statement’ button.
40. Can we edit SQL made by Crystal reports?
Ans: We cannot edit the SQL made by crystal reports. However we can view the SQL. For that select ‘Show SQL Query’ in Database menu item. Limitation is if you are using only one database. If you use two databases then you can’t even view the SQL prepared by crystal report.
41. Are there any limitations in crystal reports?
Ans: There are certain limitations in crystal reports. They are: -
1. If database is having field whose length is more than 255 characters, then you cannot make formula using that field.
2. While exporting data formatting is lost.
3. When you browse data just by right clicking on the field then it displays that is there in the database not the data selected by the query.
42. Can we suppress printing in crystal reports if 0 records are fetched?
Ans: Yes, we can suppress printing if no records are fetched. Select ‘Report Options’ in File menu item. ‘Report Options’ dialog box will pop up. In that there is one option ‘ Suppress printing if no records’ Check this option. If no records are found then nothing will be printed on the report.
43. What are the sections that we have in Crystal reports?
Ans: Report has got standard sections like ‘Page Header’, ‘Page Footer’, ‘Report Header’, ‘Report Footer’, and ‘Details’.
However you can add other sections also. Select ‘Sections’ in the Insert menu item. You can insert group sections also.
If you don’t want to show any section just right click on that section and suppress that.
44. Can we add any database field once we have chosen ‘Close’ button?
Ans: Yes, we can add any database field afterwards also. Select ‘Database Field’ in Insert menu item.
If you are using crystal report built in query then it will display the tables that you have selected. And you can select whichever field you want to display on the report.
But if you are using ‘.qry’ file then it will display Query and you can select only those field, which are there in the query.
45. Does Crystal Report support all the functions that we have in Oracle?
Ans: No, Crystal report does not support all the functions. Like Decode function is there in SQL but not there is crystal report. You need to convert that in crystal report format (in if and else etc.).
However if you use ‘.qry’ files then it take the SQL as such. There is no need of changing any syntax.
46. Can we use stored procedure for creating the report?
Ans: Yes, we can use stored procedure.
47. Is there any feature like summing total in crystal report?
Ans: Crystal reports provide features like grand total, sub-total, running total etc. You can select any of these features in Insert menu item.
You can sum up records on the basis of each record or on change of group using ‘Running Total ‘ option in Insert menu item.
48. I am using two tables one is of access database and other is of oracle database, I am getting an error saying that ‘SQL odbc error’ what should I do?
Ans: If you are getting such an error then click the icon for ‘Report Expert’. It will give a warning saying that formatting will be lost. Ignore this you will get ‘Standard Report Expert’ dialog box. Reverse the links of access database table and it will work.
49 What versions of Crystal Reports have you used?
Please indicate both release version (9, 10, XI) and type of version (.NET or standalone boxed exition, for example). A) I was willing to consider individuals who were primarily programming version users, if they were able to adequately answer questions about Crystal Reports functionality. It has been my experience, however, that "programmer" Crystal Reports writers have vastly different skill sets and opinions about solutions that "report writer" or "business user" Crystal Reports writers.
50 What is 'Set Location'
A) This is very basic Crystal Reports functionality. If the candidate doesn't know what this is, then that's a red flag.
51 Please describe, in plain English, the most complex report you've ever written. What made it complex and how did you resolve the issues that presented themselves?
A) This question helps me to understand their level of understanding of functionality, their ability to potentially address complex requirements and their creativity.
52 Have you ever written a repot against a View or Stored Procedure?
A) No? They might be skilled in Crystal Reports, but may not understand the relationship between Crystal and the database. They may also not be skilled in SQL.
53 Is it better to build a report against a View or a Stored Procedure and why? Please explain...
A) This is a very good question, in my opinion. First, the right answer is neither. It really depends on the situation. That being said, there is a contingent of report writers out there that have been brainwashed into saying a 'stored procedure is always better, because its pre-compiled'. In my opinion, this is bunk and here's
why: A stored procedure is absolutely great to use if you're going to manipulate a lot of data or crunch a lot of numbers to return aggregates. If you're simply creating a SELECT/FROM/WHERE query, it's a complete waste. Furthermore, using a Stored Procedure (or a SQL Command Object, for that matter) can severely limit the functionality you would otherwise have in Crystal Reports. For example, a common report requirement is to have a parameter that allows the user to select one, multiple or all items in the parameter list. Crystal Reports allows this functionality through multi-value parameter selection. Stored procedures do not allow this functionality...
** A View can be written to contain all of the necessary fields, joins, subqueries, etc..., but still be open enough to be used by a variety of reports. For example, I have a client who needed 15 reports, all of which were to be written against a particular module of their application. All of the reports had very similar fields, they were mostly just different in display and in the selection criteria. As such, I created a single view with both a SELECT and FROM clause, but no WHERE clause. I then built the 15 different reports all against the same view, but added selection criteria to each report. By doing so, they all used a single, easily maintainable database object, but were each unique and efficient.
55 What is a SQL Expression field in Crystal Reports? (collected from the site http://www.allinterview.com/Interview-Questions/Crystal-Reports/page3.html)

56 what is the difference between crystal reports and normal reports?
in crystal reports we can genarate reports with any type of charts (bar charts,pie charts) it is automatically genarated when we give values vto it,but that is not possible with genaral reports we manually should caluculate every thing
57 What is FSG and its use ? Financial Statement Generator is a powerful report building tool for Oracle GL. Uses of FSG :1. Generate financial reports such as income statements an
58 What is Reporting Services Microsoft SQL Server Reporting Services is server-based reporting platform similar to Crystal reports, Brio which allow you to create tabular, matrix,
59 what is different the vb.net and XML?
vb.net is product of micro soft corporation.it is for developing appication programs.
xml is an open standerd one.it is for representing data.xml is not restricted to
the particular language.we can use to represent data of any type of application.XML is common one.for bussiness to bussiness communication XML is Best one.