Difference between Varchar & Nvarchar in Sqlserver

Varchar means Variable-length Character string.
Nvarchar will store Unicode characters.Both will be used all most for the same purpose but with little difference.
Varchar will store the 8-bit data in database where as Nvarchar will be stored as 16-bit data in Database.
In Sql server 2005

The size for a table page is 8,196 bytes, and no one row in a table can be more than 8,060 characters.
This in turn limits the maximum size of a VARCHAR to 8,000 bytes.
Varchar (MAX) and Nvarchar (MAX). Varchar (MAX) can hold max of 2,147,483,648 characters and NVARCHAR (MAX) can hold 1,073,741,823 characters. We use Varchar instead of TEXT and NTEXT which cannot be used to passed as variables in a stored procedure where as Varchar (MAX) or Nvarchar (MAX) cannot have such restriction.

If you're in the process of migrating an existing data design for SQL Server 2005, it might make sense to migrate some TEXT / NTEXT fields to VARCHAR (MAX) / NVARCHAR (MAX) types when appropriate.

If you need Unicode support for a given data type, either now or soon enough, go with NVARCHAR. If you're sticking with 8-bit data for design or storage reasons, go with VARCHAR. Note that you can always migrate from VARCHAR to NVARCHAR at the cost of some room -- but you can't go the other way 'round. Also, because NVARCHAR involves fetching that much more data, it may prove to be slower depending on how many table pages must be retrieved for any given operation.

UNICODE can handle languages that are difficult to impossible with single-byte
character sets such as ASCII. If you must support many languages UNICODE is a very clean way to do it.

Create Table dynamically in sql server

I'd like to create a stored procedure that takes the name of table as a parameter, and then creates that table, if it doesn't exist, according to a schema stored somewhere.

Is that possible-- Can I store a schema and use is as a template to create tables from? Or must I hard-code the CREATE TABLE and its scheme in the stored procedure itself?

The idea here is to be able to change the schema without changing the stored procedure (separation of concerns), because I'm probably going to expand the procedure to do more.

This is as far as I got without knowing whether to just hard-code the schema for the table in the sproc, or whether I can store and pull that schema somehow.

CREATE PROCEDURE GenerateTable
@tableName as nvarchar(128)
AS
BEGIN
IF OBJECT_ID(@tableName,'U') IS NULL
CREATE TABLE @tableName ????????
ENDIF
END
GO

Find Current User Information

SELECT spid, uid=rtrim(loginame), Program_name=rtrim(Program_name),
dbname=db_name(dbid), status=rtrim(status) FROM master.dbo.sysprocesses
WHERE loginame = 'UserName';


You can also use sp_who command to see all users associated with current database.

Retrieve and Upload data From ExcelWorkbook

I got this link is very helpful when you want to upload data in bulk from the excel workbook

or you have to retrieve the data from the excel workbook.

http://support.microsoft.com/default.aspx?scid=kb;en-us;316934#12

Difference between Web Services and Remoting?

Both Remoting and Web Services are ways of communication between applications.

Remoting - In remoting, the applications involved in the communication process may be located on the same computer, different computers in a same or different network. In remoting, both applications know about each other. A proxy of an application object is created on the other application.

Web Services - Communication between applications using web services is platform independent and programming independent. The application that consumes the web service, simply accesses it, without needing to know how this web service has actually been implemented & created.

Here are some of the major differences:
* ASP.NET Web Services may be accessed using HTTP only. Remoting objects may be accessed over any protocol like TCP, SMTP, HTTP
* Web Service are Stateless, whereas Remoting has support for both stateless and with-state environment, which is achieved using Singleton and Singlecall activation
* ASP.NET provides good support to create Web Services. They are easy to deploy. In comparison, Remoting is little complex.
* Web services may be considered very reliable, due to the fact that they are hosted on IIS. In remoting, if IIS is'nt used, then methods like plumbing have to be used to ensure the application reliability.
* In .NET, when we create an application that consumes a web service, the web service may or may not be built using .NET. But while implementing Remoting in .NET, both the applications must be built in .NET.
* Using web services, only a limited number of types may be serialized (XML). Using Remoting, objects like SOAP objects, Binary objects & XML Objects may be serialized.

Different Language class file in app_code

Question : Can we keep different language class file in app_code directory at the same time?Answer : Yes we can keep the different language class file in the App_Code directory but when we try to keep the different language file in the directory it raise an error like :
Error :
'App_Code/Class2.vb' and 'App_Code/Class1.cs' use a different language, which is not allowed since they need to be compiled together.
To resolve this problem, we keep the different language class file in the different folder and we have to set the codeSubDirectories in the web.config file under the compilation tag like this

<compilation debug="true">
<codesubdirectories>
<add directoryname="CsCode">
<add directoryname="VbCode">
</codesubdirectories>
</compilation>

Convert the Rows value into CSV format

From this query you can convert row value into comma separated valuse

CREATE TABLE #tblTblValues (id int)
insert into #tblTblValues values (10)
insert into #tblTblValues values (20)
insert into #tblTblValues values (30)
insert into #tblTblValues values (40)
insert into #tblTblValues values (50)
insert into #tblTblValues values (60)
insert into #tblTblValues values (70)


DECLARE @Value varchar(2000)
SELECT @Value = COALESCE(@Value + ', ', '') + CAST(id AS varchar) FROM #tblTblValues
SELECT @Value
OutPut


10, 20, 30, 40, 50, 60, 70

Debug the Stored Procedure OR Functions in SQL?

Do you know how to debug the stored procedure OR functions in SQL?

Here the way you can debug you stored procedure and function.

Steps to debug the stored procedure/ function :

Step 1 : Create a web project/windows project according to your preference
Step 2 : Connect to your database server through server Explores (See below screenshot)
Step 3 : Expand your stored procedure/Function
Step 4 : open the procedure/ function and set breakpoint
Step 5 : Now Right click on the stored procedure / function you want to debug
Step 6 : Click on Step into stored procedure/ function
Step 7 : Set default parameter values

Now it will take to you break point.
See the screen shot below

Access Different interface method with same Name implemented in a class

We use interface and multiple interface inherit it into class, then we implement the methods of interface as it is necessary
but what will happen if two interface have the same mentods with same signature and inherited in the same class?
Now questions arises from here are :
Q1) Both the methods will be implementable which is with the same name and signature?
Q2) If methods are implementable then how it is possible?
Q3) If it is possible then can we access both the methods?
Q3) If it is possible then what is the way to access these methods publically?

The answer of all the above question is below:
1) Yes both the methods with same name and signature is implementable.
2) we have to implement interface explicitely preceding with iterface name.
3) Yes it is possible to access the methods.
4) Yes we can

Difference between an Index and a Primary Key

There seams to be some confusion between what a Primary Key is, and what an Index is and how they are used.

The Primary Key is a logical object. By that I mean that is simply defines a set of properties on one column or a set of columns to require that the columns which make up the primary key are unique and that none of them are null. Because they are unique and not null, these values (or value if your primary key is a single column) can then be used to identify a single row in the table every time. In most if not all database platforms the Primary Key will have an index created on it.

An index on the other hand doesn’t define uniqueness. An index is used to more quickly find rows in the table based on the values which are part of the index. When you create an index within the database, you are creating a physical object which is being saved to disk. Using a table which holds employees as an example:

CREATE TABLE dbo.Employee (
EmployeeId INT PRIMARY KEY,
LastName VARCHAR(50),
FirstName VARCHAR(50),
DepartmentId INT,
StartDate DATETIME,
TermDate DATETIME,
TermReason INT
)

The EmployeeId is the Primary Key for our table as that is what we will use to uniquely identify an employee. If we were to search the table based on the last name the database would need to read the entire table from the disk into memory so that we can find the few employees that have the correct last name. Now if we create an index on the LastName column when we run the same query, the database only needs to load the index from the disk into memory, which will be much quicker, and instead of scanning through the entire table looking for matches, because the values in the index are already sorted the database engine can go to the correct location within the index and find the matching records very quickly.

SQL SERVER – Delete Duplicate Records – Rows

SQL SERVER – Delete Duplicate Records – Rows « Journey to SQL Authority with Pinal Dave: "Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.


DELETE FROM MyTable WHERE ID NOT IN ( SELECT MAX(ID) FROM MyTable GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn2)

Difference between OSQL and Query Analyzer

Both are same for functioning but there is a little difference OSQL is command line tool which execute query and display the result same a Query Analyzer do but Query Analyzer is graphical.OSQL have not ability like Query Analyzer to analyze queries and show statistics on speed of execution .And other useful thing about OSQL is that its helps in scheduling which is done in Query Analyzer with the help of JOB.

Rules and Constraints in Sql Server

Rules and Constraints are similar in functionality but there is a An little diffrence between them.Rules are used for backward compatibility . One the most exclusive diffrence is that we an bind rules to a datatypes whereas constraints are bound only to columns.So we can create our own datatype with the help of Rules and get the input according to that.

Raiseerror in Sql server

Stored procedures report errors to client applications via the RAISERROR command. RAISERROR doesn’t change the flow of a procedure; it merely displays an error message, sets the @@ERROR automatic variable, and optionally writes the message to the SQL Server error log and the NT application event log.

Recursive Stored Procedure

Can a stored procedure call itself or recursive stored procedure? How many level SP nesting possible?

Yes. Because Transact-SQL supports recursion, you can write stored procedures that call themselves. Recursion can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to subsets of the problem. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps. Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code references up to 32 levels.

What is SQL server agent

SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose is to ease the implementation of tasks for the DBA, with its full-function scheduling engine, which allows you to schedule your own jobs and scripts.

Find Sql Server version & Operation System

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel')

User defined functions

User-Defined Functions allow to define its own T-SQL functions that can accept 0 or more parameters and return a single scalar data value or a table data type.


What kind of User-Defined Functions can be created?
There are three types of User-Defined functions in SQL Server 2000 and they are Scalar, Inline Table-Valued and Multi-statement Table-valued.

Scalar User-Defined Function :
A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of user-defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value.

Inline Table-Value User-Defined Function :
An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative to a view as the user-defined function can pass parameters into a T-SQL select command and in essence provide us with a parameterized, non-updateable view of the underlying tables.

Multi-statement Table-Value User-Defined Function :
A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional alternative to a view as the function can support multiple T-SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a T-SQL select command or a group of them gives us the capability to in essence create a parameterized, non-updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user-defined function, It can be used in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets.

Sub Query in sql server

Sub-queries are often referred to as sub-selects, as they allow a SELECT statement to be executed arbitrarily within the body of another SQL statement. A sub-query is executed by enclosing it in a set of parentheses. Sub-queries are generally used to return a single row as an atomic value, though they may be used to compare values against multiple rows with the IN keyword.

A subquery is a SELECT statement that is nested within another T-SQL statement. A subquery SELECT statement if executed independently of the T-SQL statement, in which it is nested, will return a result set. Meaning a subquery SELECT statement can standalone and is not depended on the statement in which it is nested. A subquery SELECT statement can return any number of values, and can be found in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a T-SQL statement. A Subquery can also be used as a parameter to a function call. Basically a subquery can be used anywhere an expression can be used.

Properties of Sub-Query :
A subquery must be enclosed in the parenthesis.
A subquery must be put in the right hand of the comparison operator, and
A subquery cannot contain a ORDER-BY clause.
A query can contain more than one sub-queries.


What are types of sub-queries?
Single-row subquery, where the subquery returns only one row.
Multiple-row subquery, where the subquery returns multiple rows,.and
Multiple column subquery, where the subquery returns multiple columns.

Difference between a HAVING CLAUSE and a WHERE CLAUSE

Specifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. HAVING criteria is applied after the the grouping of rows has occurred.

UPDATE_STATISTICS command

This command is basically used when a large processing of data has occurred. If a large amount of deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.

Difference between DELETE & TRUNCATE commands?

Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.

TRUNCATE
TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
TRUNCATE removes the data by deallocating the data pages used to store the table’s data, and only the page deallocations are recorded in the transaction log.
TRUNCATE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column.
You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.
Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
TRUNCATE can not be Rolled back using logs.
TRUNCATE is DDL Command.
TRUNCATE Resets identity of the table.

DELETE
DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.
If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement.
DELETE Can be used with or without a WHERE clause
DELETE Activates Triggers.
DELETE Can be Rolled back using logs.
DELETE is DML Command.
DELETE does not reset identity of the table.

What is Collation?

Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case-sensitivity, accent marks, kana character types and character width.


Different type of Collation Sensitivity?

Case sensitivity
A and a, B and b, etc.

Accent sensitivity
a and á, o and ó, etc.

Kana Sensitivity
When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive.

Width sensitivity
When a single-byte character (half-width) and the same character when represented as a double-byte character (full-width) are treated differently then it is width sensitive.

What is a Linked Server?

Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements. With a linked server, you can create very clean, easy to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data.

Storped Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server.

What is the use of DBCC commands?

DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.
E.g. DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.

DBCC CHECKALLOC - To check that all pages in a db are correctly allocated.
DBCC CHECKFILEGROUP - Checks all tables file group for any damage.

What is View?

A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views.

What is Trigger?

A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS.Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; the DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-drive and are not attached to a specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures.
Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger.

What is Stored Procedure?

A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.
e.g. sp_helpdb, sp_renamedb, sp_depends etc.

What is normalization?

Database normalization is a data design and organization process applied to data structures based on rules that help build relational databases. In relational database design, the process of organizing data to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.

What is RDBMS?

Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage.

Index in Sql server

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.

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.

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".

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'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 key creates a nonclustered index by default.
Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

List all tabels in database

1. SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE table_type = 'BASE TABLE'

2. SELECT name FROM dbo.sysobjects WHERE xtype = 'U'

Find duplicate columns in a Table

Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.


DELETE FROM MyTable WHERE ID NOT IN ( SELECT MAX(ID) FROM MyTable GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn2)