Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

Saturday, March 6, 2010

Daily Changes

I got a new requirement in office that I need to send the list of tables and stored procedures, I changed every day.

I was looking around and understood that in SQL SERVER 2005, INFORMATION_SCHEMA.ROUTINES and sys.tables, can give that information to me.

select [routine_name],created,last_altered from INFORMATION_SCHEMA.ROUTINES
where routine_type = 'PROCEDURE'
order by last_altered desc

select [name],create_date,modify_date from sys.tables
where [type] = 'u'
order by modify_date desc

I can now automate this in different ways now. One way will be to put this into a SSIS and send email as scheduled job.

Sunday, September 20, 2009

SQL Server Interview Questions -- Part 12 (SSRS part 2)

111. What is a Gauge in SSRS 2008 ?
Ans: Usually, the Key Performance Indicators (KPIs) in an organisation are represented using Gauge where the an indicator points to a specific value in a data range. Common example of a gauge is car speedometer.

112. Name a few new features in Report Builder 2.0.
Ans: Enhanced data layout,on-demand rendering and Rich-format text.

113. What is RDL ?
Ans: RDL is Report Definition Language that describes all the features that can be added to the SSRS report.

114. What is a Report Manager ?
Ans: A web based tool provided by Microsoft for managing and accessing reports.

115. What is Data Source Definition ?
Ans: Every report should have atleast one data source definition that explains how to connect to a data source.

116. Name a few data sources supported by SSRS 2008.
Ans: Microsoft SQL Server, Microsoft SQL Server Analysis Services, Oracle, SAP NetWeaver BI, Hyperion Essbase, Teradata, OLE DB, ODBC, and XML.

117. What is a Query Designer in SSRS 2008?
Ans: Report needs a dataset to report the information, to retrieve this dataset from database, typically you need a query. A query designer is the tool in SSRS that helps to design this query.

118. What is a shared data source in SSRS 2008 ?
Ans: If a data source is referenced by more than one report or model or data driven subscription, it is called shared data source.

119. What are advantages of shared data source ?
Ans: According to MSDN online, Shared data sources provide an easy way to manage data source properties that often change over time. If a user account or password changes, or if you move the database to a different server, you can update the connection information in one place.

120. What all does shared data source contain ?
Ans: Name, Description, Connection type, Connection string, Credential type.

Sunday, September 13, 2009

SQL Server Interview Questions -- Part 11 (SSRS part 1)

101. What is SSRS 2008 ?
Ans: A report is an organized collection of data, displayed in a readable information format. Microsoft SQL Server Reporting Services 2008 (SSRS 2008) is a server-based platform that helps to address the reporting needs of an organization.

102. What is report builder 2.0 ?
Ans: Report builder 2.0 is a report designer tool that comes as a separate installation package with SQL Server 2008.

103. What are report definition and client report definition files ?
Ans: Report definition files with .rdl extensions are created when you create a report in report builder. It may contain data sources, queries, report layout, data and other necessary reporting needs.
Client report definition files with .rdlc files are created when you create a report using Visual Studio Report Designer to be used with ReportViewer Control.

104. What is a Published Report ?
Ans: A report that is deployed on the report server for viewing is called published report.

105. What is a Rendered Report ?
Ans: Report Server process the published report into viewable output format which contains the necessary data and designed layout. The is called the rendered report which can be HTML or XML or any suitable format.

106. What are the different types of reports that can be created by SSRS 2008 ?
Ans: Ad hoc reports, Cached reports, Clickthrough reports, Drilldown reports, Drillthrough reports, Linked reports, Parameterized reports, Snapshot reports and Subreports.

107. What is a subreport ?
Ans: Subreport is a report inside a main report. Typically, when you want to use a different data source than the main report, you go for subreport.

108. What is a data region in SSRS 2008 ?
Ans: The region where the data is displayed from the dataset is the Data region and columns.

109. What are the different data regions ?
Ans: Chart, Gauge, List, Matrix and Table.

110. What is a Tablix ?
Ans: Tablix is a common term for supporting multiple rows and columns. The rows can be static or dynamic. Table, Matrix and list data regions are based on tablix.

Sunday, September 6, 2009

Basics Transactions in SQL Server 2008

A transaction in a database is a logical unit of work. A transaction can be one or more SQL statements run by a single user.

For example, If I want pay my $200 credit card bill from my bank account, it is transaction. Basically what has to happen is, the $200 has to be deducted from my bank account and it has to added to my credit card account. There are 2 SQL statements here, one to update the bank account with current balance by reducing $200 and another to add the credit card with $200 to pay it off. Both the statements has to be treated as one logical unit or transaction, because if any error happens even at one statement or if the database crashes during the statements, both of them should not happen. All actions should either fail or succeed together.

The process on executing both the statements into database and registering it is called commiting the transaction. If either one fails, not registering or moving the other one to previous state is called Rolling Back.

Syntax:

To explicitly start the transaction: Begin transaction transactionname

To explicitly commit the transaction: Commit transaction transactionname

To explicitly rollback the transaction: Rollback transaction transactionname

According to MSDN online:

BEGIN TRANSACTION represents a point at which the data referenced by a connection is logically and physically consistent. If errors are encountered, all data modifications made after the BEGIN TRANSACTION can be rolled back to return the data to this known state of consistency. Each transaction lasts until either it completes without errors and COMMIT TRANSACTION is issued to make the modifications a permanent part of the database, or errors are encountered and all modifications are erased with a ROLLBACK TRANSACTION statement.

Wednesday, August 5, 2009

Basics of Stored Procedures in SQL Server 2008

Take the following statement:

Select * from customers

This is a plain Transact-Structured Query Language (T-SQL) statement.

If you put that as,

Create procedure usp_myprocedure
as
select * from customers

It becomes a stored procedure. It is that simple. But, it gets quite complicated and has lot of uses when used extensively.

A simple definition of a stored procedure can be "A compiled set of T-SQL statements".

Some Benefits:
1. Stored procedures when registered, basically after you run the create procedure command, actually gets registered at the server.
2. They have input and output parameters that helps to take in some values and give out some other values. For example,

Create procedure usp_insertproc
@name varchar(100),
@ID int,
@print_output varchar(100) OUT
as
Begin
insert into customers (Customer_id,customer_name) values (@id, @name);
set @print_output = 'The insert was successful';
end

3. Same like any programming language, it can be created once and called from multiple places - like another stored procedure or any other application. This helps in modularity.

4. Very easy to execute. As simple as:

Exec usp_myprocedure

This also helps in reduced network traffic. Instead of sending hundreds lines of SQL code, we are sending only one.

5. Stored Procedures has good security attibutes. For example, you can give permission to a user to stored procedure but still not permission to the object that it is accessing.

6. Stored procedures are precompiled, so the same execution plan can be used when called multiple times. This makes it faster than just running a bunch of T-SQL statements.

Types of Stored procedures:

1. System Stored Procedures: They are created by SQL server itself. They are prefixed by sp_ . They can be used for lot of administrative tasks. Examples include: sp_rename; sp_who; sp_configure.

2. User-defined Stored procedures: These are the most used ones, that are created by users. Like the usp_myprocedure or the usp_insertproc examples from above.
2.a. T-SQL: If the user-defined stored procedure is created by T-SQL statements, then it is called T-SQL User-defined stored procedure.
2.b. CLR: If the user-defined stored procedure is a reference to Common Language Runtime (CLR) in .NET, then it is called CLR User-defined stored procedure.

3. Extended stored procedures: If you want to create procedures in languages such as C and use it in stored procedure, you use extended stored procedure. This is deprecated in SQL Server 2008 -- meaning it will not be available in the next version of SQL Server. So, Microsoft suggests using CLR user-defined stored procedure instead.

Sunday, July 26, 2009

SQL Server Interview Questions -- Part 10 (SSIS part 2)

91. What are event handlers in SSIS ?
Ans: Event handlers in SSIS are very similar to the event handlers in programming languages that are typically used to handle any errors raised by the SSIS package.

92. What are variables in SSIS ?
Ans: Variables store values that a SQL Server Integration Services package and its containers, tasks, and event handlers can use at run time.

93. What are log providers in SSIS ?
Ans: Log providers are the ones that are helpful in audit. You can implement log providers in packages, containers, and tasks. With logging, you can capture run-time information about a package.

94. How to run a T-SQL in SSIS ?
Ans: Execute SQL task.

95. How to run program or batch file in SSIS ?
Ans: Execute Process task.

96. What to do if you want to add custom logic to extend the control flow in SSIS ?
Ans: use the Script task.

97. What to do if you want to add custom logic to extend the data flow in SSIS ?
Ans: use Script component.

98. How to run SSIS package ?
Ans: use dtexec utility.

99. How to move or copy SSIS packages,
Ans: use the dtutil utility.

100. How to create custom extensions in SSIS ?
Ans: SSIS object model has base classes. You can create custom extensions by deriving from these base classes.

SQL Server Interview Questions -- Part 9 (SSIS part 1)

81. What is SSIS ?
Ans: SQL Server Integration Services -- commonly known as SSIS is the new platform, that was introduced in SQL Server 2005, for data transformation and data integration solutions. This replaced the DTS in SQL Server 2000.

82. Name a few SSIS components ?
Ans:
Integration Services Projects
Integration Services Packages
Control Flow Elements
Data Flow Elements
Integration Services Connections
Integration Services Variables
Integration Services Event Handlers
Integration Services Log Providers

83. What is a project in SSIS ?
Ans: A project in SSIS is a container for deleoping packages.

84. What is a package in SSIS ?
Ans: SSIS is created in Business intelligence development studio (BIDS), which is nothing but a visual studio, Package is nothing but an object. It implements the functionality of ETL -- Extract, Transform and Load -- data.

85. What are the 4 elements (tabs) that you see on a default package designer in BIDS ?
Ans: Control Flow, Data Flow, event Handler and package explorer.

86. What is a Control flow element in SSIS ?
Ans: Control flow element is one that performs any function or provide structure or control the flow of the elemtents. There must be at least one control flow element in the SSIS package.

87. What is a data flow element in SSIS ?
Ans: All ETL tasks related to data are doen by data flow elements. It is not necessary to have a data flow element in the SSIS package.


88. What are the 3 different types of control flow elements in SSIS ?
Ans:
1. Structures provided by Containers
2. Functionality provided by Tasks
3. Precedence constraints that connect the executables, containers, and tasks into an ordered control flow.

89. What are the 3 data flow components in SSIS ?
Ans:
1. Source
2. Transformation
3. Destination

90. What are connections and connection managers in SSIS ?
Ans: Connection as its name suggests is a component to connect to any source or destination from SSIS -- like a sql server or flat file or lot of other options that SSIS provides.connection manager is a logical representation of a connection.

Wednesday, July 22, 2009

Row_number(), partition and order by -- SQL Server

I had a business problem, where we had the purchase data from a website with login and the products that was purchased for last one year. My manager wanted me to just keep the latest purchase date for every login and only 3 products and delete the rest. He told i can pick any 3. May be at a later stage they want to do it based on amount of the product purchased.
I was thinking about the solution for this and thought I will create a logic in such a way that there will be a sequence id for every login and then, delete the ones above 3, so I will end up with 3 products per login. I was thinking of doing with cursor or while loop, but it will be a costly operation, so I was looking around and found this cool -- partition, Row_number() and order by combination that will do it.
I have a sample of what I did here.


The query to create the sequence is:


Monday, July 20, 2009

SQL Server Interview Questions -- Part 8

TABLEA

ID
1
2
3
4
5

TABLEB

ID
1
3
5
7

In the above tables, what is the result of
71.
select * from tableA
union
select * from tableB
Ans:

1
2
3
4
5
7

72.
select * from tableA
union all
select * from tableB
Ans:

1
2
3
3
4
5
5
7

73.
Select * from tableA
intersect
select * from tableB
Ans:

1
3
5

74.
Select * from tableA
except
select * from tableB
Ans:

2
4

75. What is a Common Table Expression (CTE) ?
Ans:
Common Table Expression can be thought of as temporary result set. But, it has lot of powers including recursive usage.

Example:
WITH MYCTE (ID, NumberOfOrders)
AS
(
SELECT ID, COUNT(*)
FROM Order
GROUP BY ID
)
select * from MYCTE


76. What is row_number() in SQL Server ?
Ans: row_number () returns the sequential number of a row in a table for all the rows. It also has a partition clause that can return sequential number starting fresh with every partition.

77. What in newid() in SQL Server ?
Ans: NewID() creates a unique value. The type of value returned by newid is a uniqueidentifier.

78. What is a temporary table in SQL Server ?
Ans: Temporary tables as the name suggests is very similar to regular table but are temporary and are stored in tempdb database.

79. What are the two types of temporary tables in SQL Server ?
Ans: Local and Global.

80. What are the difference between local and global temporary tables ?
Ans: Local tables are represented as #temp and global ones are represented as ##temp. Local temporary tables can been seen/accessed by only the user who creates it and are deleted when the user disconnects from the current instance of SQL Server. Global temporary tables can be seen/accessed by any user and are deleted only when all users referencing the table disconnect from the instance of SQL Server.

Friday, July 10, 2009

SQL Server Interview Questions -- Part 7

61. How do you check the version number of the SQL Server you are currently running ?
Ans: select @@version

62. What is use of sp_who ?
Ans: Currently running users and process in SQL Server can be found by running sp_who.

63. What is sp_who2 ?
Ans: It shows little more that sp_who with locking, blocking, what the users logged in are doing and so on.

64. What is a linked server in SQL Server ?
Ans: From your current SQL server management stuio/querey analyzer, if you want to execute commands against OLE DB data sources on remote servers, you use linked server.

65. Write a query to list all the user defined tables in SQL Server 2008 ?
Ans: select * from sys.objects where type = 'U'

66. What is instead of trigger in SQL Server ?
Ans: Instead of triggers -- are triggers attached to table in which, the code inside them is executed in place of the original insert/delete/update statement

67. What are DBCC commands in SQL Server 2008 ?
Ans: Database Console Commands -- DBCC -- are used for Maintenance, Information, Validation and Miscellaneous -- tasks in SQL Server

68. What is DBCC DBREINDEX in SQL Server 2008 ?
Ans: DBCC DBREINDEX is used to rebuilds indexes for a table. Please note that it is deprecated in SQL SERVER 2008 and will be removed in the next version. It will be replaced by REBUILD option in Alter Index.

69. What are the default databases in SQL Server 2008 ?
Ans: tempdb, model, msdb, master

70. What is the NOLOCK in SQL Server 2008 ?
Ans: NOLOCK command asks the SQL Server to ignore the locking. For example,
SELECT * from TableA WITH NOLOCK
JOIN TABLEB WITH NOLOCK ON TABLEA.ID = TABLEB.ID

Thursday, July 2, 2009

SQL Server Interview Questions -- Part 6

In MSDN online, there is a Maximum Capacity Specifications for SQL server different versions. It is hard to remember all of them. These are the most common ones that are asked in interviews. These specifications are for 32-bit enterprise edition of sql server 2008.

51. Maximum number of columns used in GROUP BY, ORDER BY in SQL Server 2008:
Ans: It is not limited by number of columns but it is limited by number of bytes. The maximum bytes per GROUP BY, ORDER BY is 8060.

52. What is the maximum number of clustered index per tables in SQL Server 2008 ?
Ans: 1

53. What is the maximum number of columns per select or insert statement in SQL Server 2008 ?
Ans: 4096

54. What is the maximum Database size in SQL Server 2008 ?
Ans: 524,272 terabytes

55. What is the maximum number of databases per instance of SQL Server 2008 ?
Ans: 32,767

56. What is maximum number of non-clustered index per table in SQL Server 2008 ?
Ans: 999

57. What is the maximum number of parameters in stored procedures or user defined functions in SQL Server 2008 ?
Ans: 2,100

58. What is the maximum number of rows a table can have in SQL Server 2008 ?
Ans: It is limited only by the storage.

59. What is the nesting maximum for stored procedures/triggers/subqueries in SQL Server 2008.
Ans: 32

60. What is the maximum bytes per row in SQL Server 2008 ?
Ans: 8,060

Wednesday, June 24, 2009

SQL Server Interview Questions -- Part 5

41. What is Resource Governor in SQL Server 2008 ?
Ans: The Resource Governor is a tool given by SQL Server 2008 to control and allocate CPU and memory resources depending on the priority of applications.

42. What is External key management in SQl Server 2008 ?
Ans: If there is a way to store key and data to be stored seperately on the encryption, it is the best way for security. External Key Management enables this and allows keys to be stored by third-party.

43. What is the new buzz word LINQ to SQL in 2008 ?
Ans: .NET 3.5's solution for querying SQL is Language Integrated Query (LINQ) to SQL where in tables are stored as objects.

44. What is Table-Valued Parameters in SQL Server 2008 ?
Ans: Table-Valued Parameters (TVPs) are the output or input parameters of stored procedures that can accept or return table as parameters rather than just one value at a time as in earlier versions of SQL Server.

45. What is Large User Defined Type in SQL Server 2008 ?
Ans: In SQL Server 2008, large user-defined types (UDTs) can create custom user defined data type of size limit of 2 GB compared to the previous 8 KB.

46. What is new in backup compression in SQL Server 2008 ?
Ans: Backup can be compressed in sql serevr 2008 without actually compressing the database itself. The is data automtically decompressed when data is restored.

47. What is hot add CPUs in SQL Server 2008 ?
Ans: One of the new features in SQL Hot-add CPUs. This feature allows the addition of extra CPUs to the server without having to actually shutdown the server.

48. What is special of Data encrytion in SQL Server 2008 ?
Ans: In SQL Server 2008, data can be encrypted and stored securely by Transparent Data Encryption.

49. Name one CLR improvement in SQL Server 2008.
Ans: Common Language Runtime (CLR) has table-valued functions. Now, to run the query more efficiently, an order clause can be used in the create function.

50. What is spatial index in SQL Server 2008 ?
Ans: SQL Server 2008 introduced the support for spatial datatypes as new feature. The index that is created on a spatial column in the table is called spatial index.

Saturday, June 20, 2009

SQL Server Interview Questions -- Part 4

31. What are the new spatial datatypes in sql server 2008 ?
Ans: Geography and Geometry. Flat data -- such as planar is supported by the geometry data type. Round earth data, such as latitude and longitude, is supported by the geography data type.

32. What is new in date time in sql server 2008 ?
Ans: In the previous versions of SQL server, date and time cannot be stored seperately. In 2008, there are 2 new seperate datatypes -- date and time.

33. What is the new hierarchyid data type in sql server 2008 ?
Ans: Hierarchyid is new datatype introduced to easily store hierarchy data such as organisational structure.

34. What is sparse column in sql server 2008 ?
Ans: A sparse column is a special type of column that has been optimized for columns that has lot of null values. It is recommended to declare a column sparse, if the column has or is expected to have more than 20% null.

35. What is new in Filtered Indexes and Statistics in sql server 2008 ?
Ans: In 2008, we indicate filtered indexes and statistics on specific subset of rows, that are well defined, like the ones that has null.

36. what is new in lock escalation in sql server 2008 ?
Ans: Lock Escalation option in alter table of 2008 allows disabling of lock escalation on the table.

37. How is error handling different in sql serve 2008 ?
Ans: Finally, sql server 2008 allows use of try..catch to handle errors.

38. What is new in sql server 2008 TDE ?
Ans: There is a new option for the who database to be automatically encrypted using Transparent data encryption (TDE).

39. What is new in backup in sql server 2008 ?
Ans: Backup Compression in sql server 2008 supports compressing the backups and storing at a less disk space.

40. What is news in Audting in sql server 2008 ?
Ans: customized audits of database events can be created using SQL Server 2008 Audit functionality.

Wednesday, June 17, 2009

SQL Server Interview Questions -- Part 3

21. What is a user defined function (udf) ?
Ans: UDF is very similar to functions created in any programming language but with SQL statements. So, it can be defined as database unit of work created using SQL commands.

22. Compare UDFs and Stored procedure ?
Ans: UDFs can be used in select, where, join or case statements while SPs cannot be. UDFs cannot be used in DML statements to modify, while we can use them in stored procedures.

23. When do you use cursor ?
Ans: If you have to process one row at a time and loop through a set of rows, you can use cursors.

24. What are the special tables that can be used only within trigger ?
Ans: "Inserted" to check the rows inserted through the trigger and "Deleted" to check the rows deleted through the trigger.

TABLEA

ID
1
2
3

TABLEB

ID
1
3
5

25. What is the result of Select * from TABLEA A join TABLEB B on a.ID = b.ID ?
Ans:
1 1
3 3

26. What is the result of Select * from TABLEA A left join TABLEB B on a.ID = b.ID ?
Ans:
1 1
2 null
3 3


27. What is the result of Select * from TABLEA A right join TABLEB B on a.ID = b.ID ?
Ans:
1 1
3 3
null 5

28. What are the types of indexes ?
Ans: Clustered and non-clustered index

29. What is the difference between clustered and non-clustered index ?
Ans: Clustered index is a special kind of index in which the node of the B tree has the actual value. so, clustered index can be created only on table that has unique non null values.
Non-Clustered index has a pointer to the actual node.

30. What is a getdate() ?
Ans: getdate() returns the current system timestamp.

Sunday, June 14, 2009

SQL Server Interview Questions -- Part 2

11. By using group by, check for duplicate names in test table
Ans: select [name],count(*) from test
group by [name]
having count(*) > 1

12. What is a database transaction ?
Ans: A database transaction is the smallest unit of work in a database.

13. What is are properties of database transaction ?
Ans: A database transaction always comply with ACID properties -- Atomicity, Consistency, Isolation and Durability.

14. What are the different Isolation levels ?
Ans: Read uncommitted, Read committed, Repeatable Read and Serializable.

15. What is differnce between DELETE and TRUNCATE ?
Ans: DELETE is a logged operation. So, each row deleted is logged in the transaction log.
TRUNCATE is not a logged operatio. So, each row is not entered in transaction log.
The logging makes the DELETE slower than TRUNCATE.

16. Name a few datatypes in SQL Server 2008
Ans: Date, Time, Datatime2, Geometry, hierarchyid...

17. What is datetime2 ?
Ans: It is the extension of current datetime where the date range can be from Jan 1, 0001 AD to dec 31, 9999 AD.
Also, the time range can be from 00:00:00 to 23:59:59.9999999

18. What is a stored procedure ?
Ans: Stored Procedure is a set of transact SQL statements that are pre compiled and stored in database.

19. What is a trigger ?
Ans: Trigger is a special kind of stored procedure, that is run automatically by the database, depending on the transaction it is registered for like insert, update and/or delete.

20. What is a database index ?
Ans: Database index is same as the index in a book. It helps to find the required row faster.

Saturday, June 13, 2009

SQL Server Interview Questions -- Part 1

1. What is a Database ?
Ans: A database is a structured collection of data in computer using one of the database models.

2. What is a Database Management System ?
Ans: A Database Management System (DBMS) is a software that organizes and manages the data in the database.

3. What is a Relational Database Management System ?
Ans: A Relational Database Management System (RDBMS) is a DBMS that uses relational database model. Relational database model is one that organizes data in Attributes(columns) and Tuples(Rows).

4. What is normalization ?
Ans: Normalization is the process of reducing the redundancy in data in the RDBMS.

5. What is de-normalization ?
Ans: De-normalization is the process of introducing controlled redundancy of data in the RDBMS. It is the reverse process of normalization.

6. How to create a table and insert the data, from another table in the same database, in one query ?
Ans: Select * into table2 from table1

7. How to create a table structure and not data, from another table in the same database, in one query ?
Ans: Select * into table2 from table1 where 1 = 2
Here we can give any where clause that doesnot return any rows.

8. Write a simple insert statement to insert one row into employee table whose employee id is 1, name is Joe Paul.
Ans: insert into employee (employee_id, first_name, last_name) values (1, 'Joe', 'Paul')

9. Write a simple delete statement to delete user with id 2 from the system
Ans: Delete from employee where employee_id = 2

10. Write an update statement to give 2.3% increase in salary for all employees in compensation table
Ans: update compensation set salary = salary + (salary * (2.3/100))