Tuesday, December 22, 2009
Monday, December 21, 2009
Difference between Temp table and Table Variables
http://blog.sqlauthority.com/2009/12/15/sql-server-difference-temptable-and-table-variable-temptable-in-memory-a-myth/
and must read the comments section it is also ultimate.......
Tuesday, December 15, 2009
Sunday, December 13, 2009
Tuesday, November 24, 2009
paypal working (must see for payment gateway integration)
Wednesday, October 28, 2009
SOAP and BINARY formatter serialization
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Reflection;
using System.Globalization;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Formatters.Binary;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
secreteClass obj = new secreteClass();
obj.MyAccNum = 123321456;
obj.Passwd="newPassword";
//// SOAP FORMATTER
SoapFormatter formatter = new SoapFormatter();
Stream objfilestream = new FileStream("c:\\Myserialzed.xml", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(objfilestream, obj);
objfilestream.Close();
//deserialization
Stream objreadstream = new FileStream("c:\\Myserialzed.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
secreteClass objSecrete2 = (secreteClass)formatter.Deserialize(objreadstream);
int Myaccno = objSecrete2.MyAccNum;
Response.Write ("AccNo:{0} " + Myaccno.ToString());
//// BINARY FORMATTER
BinaryFormatter bformatter = new BinaryFormatter();
Stream objbfilestream = new FileStream("c:\\Myserialzed.txt", FileMode.Create, FileAccess.Write, FileShare.None);
bformatter.Serialize(objbfilestream, obj);
objbfilestream.Close();
//deserialization
Stream objBreadstream = new FileStream("c:\\Myserialzed.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
secreteClass objBSecrete2 = (secreteClass)bformatter.Deserialize(objBreadstream);
}
}
[Serializable]
public class secreteClass
{
private int myaccountnumber = 0;
[NonSerialized()]
private string password = "qwerty321";
public int MyAccNum
{
get
{
return myaccountnumber;
}
set
{
myaccountnumber = value;
}
}
public string Passwd
{
get
{
return password;
}
set
{
password = value;
}
}
public secreteClass()
{
}
public void SerializedMethod()
{
}
}
Thursday, October 22, 2009
Delay sigining
During development process you will need strong name keys to be exposed to developer which is not a good practice from security aspect point of view.In such situations you can assign the key later on and during development you an use delay signing
Following is process to delay sign an assembly:
First obtain your string name keys using SN.EXE.
Annotate the source code for the assembly with two custom attributes from System.Reflection: AssemblyKeyFileAttribute, which passes the name of the file containing the public key as a parameter to its constructor. AssemblyDelaySignAttribute, which indicates that delay signing, is being used by passing true as a parameter to its constructor.
For example as shown below:
C#
using System;
using System.Reflection;
[assembly:AssemblyKeyFileAttribute("TestPublicKey.snk")]
[assembly:AssemblyDelaySignAttribute(true)]
namespace DelaySign
{
public class Test { }
}
When this attribute is used on an assembly, space is reserved for the signature which is later filled by a signing tool such as the Sn.exe utility. Delayed signing is used when the author of the assembly does not have access to the private key that will be used to generate the signature, as in [assembly:AssemblyDelaySignAttribute(true)].
The compiler inserts the public key into the assembly manifest and reserves space in the PE file
for the full strong name signature. The real public key must be stored while the assembly is built
so that other assemblies that reference this assembly can obtain the key to store in their own
assembly reference.
• Because the assembly does not have a valid strong name signature, the verification of
that signature must be turned off. You can do this by using the –Vr option with the
Strong Name tool. The following example turns off verification for an assembly called
myAssembly.dll.
Sn –Vr myAssembly.dll
• Just before shipping, you submit the assembly to your organization signing authority
for the actual strong name signing using the –R option with the Strong Name tool. The
following example signs an assembly called myAssembly.dll with a strong name using the
sgKey.snk key pair.
Sn -R myAssembly.dll sgKey.snk
The compiler inserts the public key into the assembly manifest and reserves space in the PE file for the full strong name signature. The real public key must be stored while the assembly is built so that other assemblies that reference this assembly can obtain the key to store in their own assembly reference.
Because the assembly does not have a valid strong name signature, the verification of that signature must be turned off. You can do this by using the -Vr option with the Strong Name tool.The following example turns off verification for an assembly called myAssembly.dll.
Just before shipping, you submit the assembly to your organization's signing authority for the actual strong name signing using the -R option with the Strong Name tool. The following example signs an assembly called myAssembly.dll with a strong name using the sgKey.snk key pair.
Tuesday, October 6, 2009
Reflaction and example
Reflection
To read method, prop, construtor, etc from assembly.
We can create assembly at run time
When we use c# dll in vb, and two variables a and A can also be used using reflection
Create new class liabrary (new project in c#)
Public class class1
{
Private int32 eno , es;
Private string en,ed;
Public class1()
{
}
Public class1 ( int32 a, string b, string c, int32 d)
{
Eno = a; ed= c; en=b; es = d;
}
Public int32 p_empno
{
Get
{
Return eno;
}
Set
{
Eno =value;
}
}
Public string p_ename
{
Get
{
Return en;
}
Set
{
En =value;
}
}
Public string p_eadd
{
Get
{
Return ed;
}
Set
{
Ed =value;
}
}
Public int32 p_esal
{
Get
{
Return es;
}
Set
{
Es = value;
}
}
Public int32 callall()
{
Return p_sal * 10 /100;
}
Public int32 calded(int32 pf, int32 tax)
{
Return p_esal * pf/100 + p_esal * tax / 100;
}
}
Compile this class file
Create new web site in c#
Default.aspx;
Code
Using System.reflection;
Type typ = null;
Pageload()
{
Assembly asm = assembly.loadfile(“d:\\classliabrary24 \\classlibrary24\\bin\\debug\\classlibrary24.dll”); //path of dll file
Type[] typs = asm.gettypes; //element of class may be more than one
Typ = asm.gettype(typs[0].tostring());
}
Design
Button1 button2 button3 button4
Button1()
{
Constructorinfo[] ci = typ.getconstructors();
//all constructors in class lib
Int32 I;
For(i=0; i<>
{
Response.write(ci[i].tostring() + “
”);
}
}
Button2()
{
Propertyinfo[] pi = typ.getproperty();
Int32 I;
For(i=0;i
{
Resoponse.write(pi[i].tostring() + “
”);
}
}
Button3()
{
Methodinfo[] mi = typ.getmethods();
Int32 I;
For(i=0;i
{
Response.write(mi[i].tostring() + “
”);
}
}
Button4()
{
Constructorinfo[] ci = typ.getconstructors();
Object obj = activator.createinstance(typ);
//Ci[0].invoke(obj,null); //calling default constructor
Object[] ar = new object[4];
Ar[0] = 10;
Ar[1]=”vikas”;
Ar[2]=”#2223”;
Ar[3]=12000;
Ci[1].invoke(obj,ar);
Propertyinfo[] pi = typ.getproperties();
Response.write(pi[0].getvalue(obj,null).tostring() + “
”);
//to read from property getvalue used
Response.write(pi[1].getvalue(obj,null).tostring() + “
”);
Response.write(pi[2].getvalue(obj,null).tostring() + “
”);
}
Add one more button5
Button5()
{
Propertyinfo[] pi = typ.getproperties();
Object obj = activator.createinstanse(typ);
Pi[0].setvalue(obj,101,null);
Pi[1].setvalue(obj,”aman”,null);
Pi[2].setvalue(obj,”#23adsf”,null);
Pi[3].setvalue(obj,23000,null);
Methodinfo[] mi = typ.getmethods();
Int32 k = (int32)(mi[8].invoke(obj,null));
Response.write(k.tostring() + “
”);
Object[] ar = new object[2];
Ar[0]=20;
Ar[1]=30;
Int32 k1 (int32)(mi[9].invoke(obj,ar));
Response.write(k1.tostring());
}
Add new page:
--------------
Default2.aspx:
Textbox1 Button1
Code:
Using system.reflection;
Using system.reflection.emit;
//emit namespace is used for
Pageload()
{
}
Private assembly abc()
{
Assemlyname nam = new assemblyname();
Nam.name = “myfirstasm”;
Assemblybuilder asmbul = appdomain.currentdomain. definedynamicassembly(nam,assemblybuilderaccess.runandsave,”e:\\abc”);
//current area of app where it is running
//assemblybuilderaccess is used for the type of assmb at runtime, run save or both
//very useful for security purpose
Modulebuilder modbul = asmbul.definedynamicmodule (“myfirstasm”,”myfirstasm.dll”);
// for making namespace
Typebuilder typbul = modbul.definetype(“clsabc”,typeattributes.public | typeattributes.class);
//for making class
Type[] ar = new type[]{typeof(int32),typeof(int32)};
//prototype of a method
Methodbuilder metbul = typbul.definemethod(“sum”,methodattribute.public, typeof(int32), ar);
// for making runtime method
Parameterbuilder p1 = metbul.defineparameter(1, parameterattributes.in, “n1”);
Parameterbuilder p2 = metbul.defineparameter(2, parameterattributes.in, ”n2”);
Ilgenerator ilgen = metbul.getilgenerator();
//for generating msil
Ilgen.emit(opcodes.lgarg_1);
//ldarg_1 stores in stack
Ilgen.emit(opcodes.ldarg_2);
Ilgen.emit(opcodes.add);
Ilgen.emit(opcodes.ret);
Typbul.createtype();
Asmbul.save(“myfirstasm.dll”);
Return asmbul;
}
Button1()
{
Assembly asm = abc();
Type typ = asm.gettype(“clsabc”);
Object obj = activator.createinstance(typ);
Object[] ar = new object[2];
Ar[0]=350;
Ar[1]=500;
Int32 k = (int32) ( typ.invokemember(“sum”,bindingflags.invokemethod,null, obj, ar);
//name of method, invoking method, overloading situation, object name, parametr
Textbox1.text = k.tostring();
}
Sunday, October 4, 2009
connection Pooling
Default value of Max Pool size is 100.You can set that in SQL Connection String...e.g"Server=(local); ..........; Database=Northwind; Max Pool Size=45; Min Pool Size=10When a connection is opened and a pool is created, multiple connections are added to the pool to bring the connection count to the configured minimum level. Connections can be subsequently added to the pool up to the configured maximum pool count. When the maximum count is reached, new requests to open a connection are queued for a configurable duration.
Creating a Connection Pool
Each connection pool is associated with a specific connection string. By default, the connection pool is created when the first connection with a unique connection string connects to the database. The pool is populated with connections up to the minimum pool size.
Additional connections can be added until the pool reaches the maximum pool size.
The pool remains active as long as any connections remain open, either in the pool or used by an application with a reference to a Connection object that has an open connection.
If a new connection is opened and the connection string does not exactly match an existing pool, a new pool must be created. By using the same connection string, you can enhance the performance and scalability of your application.
In the following C# code fragment, three new DbConnection objects are created, but only two connection pools are required to manage them. Note that the connection strings for conn1 and conn2 differ by the values assigned for User ID, Password, and Min Pool Size connection string options.
DbProviderFactory Factory = DbProviderFactories.GetFactory("DDTek.Oracle");
DbConnection Conn1 = Factory.CreateConnection();
Conn1.ConnectionString = "Host=Accounting;Port=1521;User ID=scott;Password=tiger; " +
"Service Name=ORCL;Min Pool Size=50";
Conn1.Open();
// Pool A is created and filled with connections to the
// minimum pool size
DbConnection Conn2 = Factory.CreateConnection();
Conn2.ConnectionString =
"Host=Accounting;Port=1521;User ID=Jack;Password=quake; " +
"Service Name=ORCL;Min Pool Size=100";
Conn2.Open();
// Pool B is created because the connections strings differ
DbConnection Conn3 = Factory.CreateConnection();
Conn3.ConnectionString =
"Host=Accounting;Port=1521;User ID=scott;Password=tiger; " +
"Service Name=ORCL;Min Pool Size=50";
Conn3.Open();
// Conn3 is assigned an existing connection that was created in
// Pool A when the pool was created for Conn1
Once created, connection pools are not destroyed until the active process ends or the connection lifetime is exceeded. Maintenance of inactive or empty pools involves minimal system overhead.
Wednesday, September 30, 2009
Difference between Linklist and list (Generics)
http://stackoverflow.com/questions/128636/net-data-structures-arraylist-list-hashtable-dictionary-sortedlist-sortedd
Tuesday, September 29, 2009
sql questions
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 nonclustered 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.
Back to top
SQL Server architecture
(top)
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 KEYFor an explanation of these constraints see books online for the pages titled: "Constraints" and "CREATE TABLE", "ALTER TABLE"
Whar 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.
Back to top
Database administration
(top)
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 index2) 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 repopulated3) Database is upgraded from a previous versionLook 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.
Back to top
Database programming
(top)
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 hikeSalary between 40000 and 55000 -- 7000 hikeSalary between 55000 and 65000 -- 9000 hikeIn 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 + 5000WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000ENDAnother 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_settriggerorderTriggers 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 t2WHERE 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 JOINemp t2ON t1.mgrid = t2.empid
Given an employee table, how would you find out the second highest salary?
Extension methods in .Net
exp:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
Ref link:
--------
http://msdn.microsoft.com/hi-in/library/bb383977(en-us).aspx
Tuesday, September 22, 2009
The ALTER TABLE statement allows you to rename an existing table. It can also be used to add, modify, or drop a column from an existing table.
Renaming a table
The basic syntax for renaming a table is:
ALTER TABLE table_name RENAME TO new_table_name;
For example:
ALTER TABLE suppliers RENAME TO vendors;
This will rename the suppliers table to vendors.
Adding column(s) to a table
Syntax #1
To add a column to an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name ADD column_name column-definition;
For example:
ALTER TABLE supplier ADD supplier_name varchar2(50);
This will add a column called supplier_name to the supplier table.
Syntax #2
To add multiple columns to an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name
ADD (
column_1
column-definition,
column_2
column-definition,
...
column_n
column_definition );
For example:
ALTER TABLE supplier
ADD (
supplier_name
varchar2(50),
city
varchar2(45) );
This will add two columns (supplier_name and city) to the supplier table.
Modifying column(s) in a table
Syntax #1
To modify a column in an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name MODIFY column_name column_type;
For example:
ALTER TABLE supplier MODIFY supplier_name varchar2(100) not null;
This will modify the column called supplier_name to be a data type of varchar2(100) and force the column to not allow null values.
Syntax #2
To modify multiple columns in an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name
MODIFY (
column_1
column_type,
column_2
column_type,
...
column_n
column_type );
For example:
ALTER TABLE supplier
MODIFY (
supplier_name
varchar2(100)
not null,
city
varchar2(75)
);
This will modify both the supplier_name and city columns.
Drop column(s) in a table
Syntax #1
To drop a column in an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name DROP COLUMN column_name;
For example:
ALTER TABLE supplier DROP COLUMN supplier_name;
This will drop the column called supplier_name from the table called supplier.
Rename column(s) in a table(NEW in Oracle 9i Release 2)
Syntax #1
Starting in Oracle 9i Release 2, you can now rename a column.
To rename a column in an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name RENAME COLUMN old_name to new_name;
For example:
ALTER TABLE supplier RENAME COLUMN supplier_name to sname;
This will rename the column called supplier_name to sname.
Acknowledgements: Thanks to Dave M., Craig A., and Susan W. for contributing to this solution!
Practice Exercise #1:
Based on the departments table below, rename the departments table to depts.
CREATE TABLE departments
(
department_id
number(10)
not null,
department_name
varchar2(50)
not null,
CONSTRAINT departments_pk PRIMARY KEY (department_id)
);
Solution:
The following ALTER TABLE statement would rename the departments table to depts:
ALTER TABLE departments RENAME TO depts;
Practice Exercise #2:
Based on the employees table below, add a column called salary that is a number(6) datatype.
CREATE TABLE employees
(
employee_number
number(10)
not null,
employee_name
varchar2(50)
not null,
department_id
number(10),
CONSTRAINT employees_pk PRIMARY KEY (employee_number)
);
Solution:
The following ALTER TABLE statement would add a salary column to the employees table:
ALTER TABLE employees ADD salary number(6);
Practice Exercise #3:
Based on the customers table below, add two columns - one column called contact_name that is a varchar2(50) datatype and one column called last_contacted that is a date datatype.
CREATE TABLE customers
(
customer_id
number(10)
not null,
customer_name
varchar2(50)
not null,
address
varchar2(50),
city
varchar2(50),
state
varchar2(25),
zip_code
varchar2(10),
CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);
Solution:
The following ALTER TABLE statement would add the contact_name and last_contacted columns to the customers table:
ALTER TABLE customers
ADD (
contact_name
varchar2(50),
last_contacted
date );
Practice Exercise #4:
Based on the employees table below, change the employee_name column to a varchar2(75) datatype.
CREATE TABLE employees
(
employee_number
number(10)
not null,
employee_name
varchar2(50)
not null,
department_id
number(10),
CONSTRAINT employees_pk PRIMARY KEY (employee_number)
);
Solution:
The following ALTER TABLE statement would change the datatype for the employee_name column to varchar2(75):
ALTER TABLE employees MODIFY employee_name varchar2(75);
Practice Exercise #5:
Based on the customers table below, change the customer_name column to NOT allow null values and change the state column to a varchar2(2) datatype.
CREATE TABLE customers
(
customer_id
number(10)
not null,
customer_name
varchar2(50),
address
varchar2(50),
city
varchar2(50),
state
varchar2(25),
zip_code
varchar2(10),
CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);
Solution:
The following ALTER TABLE statement would modify the customer_name and state columns accordingly in the customers table:
ALTER TABLE customers
MODIFY (
customer_name
varchar2(50) not null,
state
varchar2(2) );
Practice Exercise #6:
Based on the employees table below, drop the salary column.
CREATE TABLE employees
(
employee_number
number(10)
not null,
employee_name
varchar2(50)
not null,
department_id
number(10),
salary
number(6),
CONSTRAINT employees_pk PRIMARY KEY (employee_number)
);
Solution:
The following ALTER TABLE statement would drop the salary column from the employees table:
ALTER TABLE employees DROP COLUMN salary;
Practice Exercise #7:
Based on the departments table below, rename the department_name column to dept_name.
CREATE TABLE departments
(
department_id
number(10)
not null,
department_name
varchar2(50)
not null,
CONSTRAINT departments_pk PRIMARY KEY (department_id)
);
Solution:
The following ALTER TABLE statement would rename the department_name column to dept_name in the departments table:
ALTER TABLE departments RENAME COLUMN department_name to dept_name;
Check User availablity through Jquery and ajax
First Step : Create page for check user name
$(document).ready(function() {
$("#txtUserName").blur(function(e) {
if ($("#txtUserName").val().length > 5) {
setTimeout(function() { onChange(); }, 500);
}
else {
$("#img").fadeOut('normal');
$("#lblMsg").remove();
$("#imgin").remove();
$("#txtUserName").focus();
$("#img").append('Enter Minimum 6 Character');
$("#img").fadeIn('slow');
}
});
$("# txtUserName ").keypress(function(e) {
if ($("#txtUserName ").val().length > 5) {
// track last key pressed
lastKeyPressCode = e.keyCode;
switch (e.keyCode) {
case 38: // up
e.preventDefault();
moveSelect(-1);
break;
case 40: // down
e.preventDefault();
moveSelect(1);
break;
case 9: // tab
case 13: // return
if (selectCurrent()) {
// make sure to blur off the current field
$input.get(0).blur();
e.preventDefault();
}
break;
default:
setTimeout(function() { onChange(); }, 500);
break;
}
}
});
function onChange() {
$.ajax({
type: "POST",
url: "webform1.aspx",
data: "val=" + $("# txtUserName ").val(),
success: function(msg) {
if ($(msg).find("#lbl").html() == 'Available') {
//$("#lbl").text($(msg).find("#lbl").html());
$("#img").fadeOut('normal');
$("#imgin").remove();
$("#lblMsg").remove();
$("#img").append('');
$("#img").fadeIn('slow');
}
else {
$("#img").fadeOut('normal');
$("#imgin").remove();
$("#lblMsg").remove();
$("#txtUserName").focus();
$("#img").append('');
$("#img").fadeIn('slow');
}
}
});
}
});
2nd step : to access data from database
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["val"]!=null)
{
SqlConnection connectrion =new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
connectrion.Open();
string cmdText = "select 1 from userlogin(nolock) where username='" + Request.Form["val"].ToString()+"'";
SqlCommand com = new SqlCommand(cmdText);
com.Connection = connectrion;
string result;
result = Convert.ToString(com.ExecuteScalar());
connectrion.Close();
if (result =="1")
lbl.Text = "Available";
else
lbl.Text = "Not Available";
}
else
{
lbl.Text = "false";
}
}
Saturday, September 19, 2009
SQL Server 2008: Change Data Capture (CDC)
Introduction
One of SQL Server 2008's biggest BI features being touted is Change Data Capture (CDC). CDC is basically suppose to be a built-in solution to the old-age practice in ETL solutions of identifying and using change identifiers columns in source systems. I have now spent a fair amount of time using this feature and more importantly how to leverage it inside of SSIS packages for incremental ETL solutions. My work here has been to prepare for an upcoming demonstration of CDC in SSIS. This post/Q&A is a brief summary of my findings thus far...
*CDC is being positioned as the 'design of choice' for SQL Server 2008+ OLTP database servers for exposing changed relational data for data warehousing consumption purposes.
What is Change Data Capture (CDC)?
CDC records (or captures) DML activity on designated tables. CDC works by scanning the transaction log for a designated table's 'captured columns' whose content has changed and then making those changes available for data syncronizing purposes in a relational format. As you can see this feature in entrenched in transaction log architecture and thus alot of the metadata in CDC is related around the concept of a Log Sequence Number (LSN).
So whats a LSN?
Here is the definition of a LSN per Books Online: "Every record in the Microsoft SQL Server transaction log is uniquely identified by a log sequence number (LSN). LSNs are ordered such that if LSN2 is greater than LSN1, the change described by the log record referred to by LSN2 occurred after the change described by the log record LSN. "
How do I get CDC?
CDC is a feature of SQL Server 2008 Enterprise, Developer, and Evaluation editions.
What are the target applications or consumers of the CDC technology?
ETL Solutions are the most common, however any data consuming application that requires syncronizing data could benefit from the technology.
Is CDC configurable via a UI or just TSQL?
As of this time, just TSQL.
How do you configure CDC?
1. Enable CDC for a database
1. Enables the current database via the USE statement *select is_cdc_enabled from sys.databases where [name] = 'AdventureWorks' to determine if DB is allready enabled *Also note that when you do this all of the below system objects get created in the selected database
2. Enable CDC for a given table and it's selected columns
1. Specify the captured table's schema, name, database role, capture instance name (defaults to schema_name), support net changes (bit, set it to 1 if you want both change data table-valued functions created), name of captured table's unique index, captured column list (null/default to all columns), filegroup for the change table (null/defaults to default filegroup)
3. Query Change Data via 1 of 2 built in table-valued functions created during step #2
1. For all changes (meaning a row is returned for each DML) use cdc.fn_cdc_get_all_changes_
2. For the net changes (meaning one row returned for each source row modified among 1 or more DMLs) use cdc.fn_cdc_get_net_changes_
What are all of the CDC system objects available to me?
System Tables:
o cdc.captured_columns
o cdc.change_tables
o cdc.ddl_history
o cdc.index_columns
o cdc.lsn_time_mapping
o cdc.Schema_Name_CT (change tables) *this is just the default naming convention, configurable via the enable table sysproc
DMVs:
o sys.dm_cdc_log_scan_sessions
o sys.dm_repl_traninfo
o sys.dm_cdc_errors
System Stored Procedures:
o sys.sp_cdc_enabledb
o sys.sp_cdc_disabledb
o sys.sp_cdc_cleanup_change_table
o sys.sp_cdc_disable_db_change_data_capture
o sys.sp_cdc_disable_table_change_data_capture
o sys.sp_cdc_enable_db_change_data_capture
o sys.sp_cdc_enable_table_change_data_capture
o sys.sp_cdc_get_ddl_history
o sys.sp_cdc_get_captured_columns
o sys.sp_cdc_help_change_data_capture
System Functions:
o cdc.fn_cdc_get_all_changes_
o cdc.fn_cdc_get_net_changes_
o sys.fn_cdc_decrement_lsn
o sys.fn_cdc_get_column_ordinal ( 'capture_instance' , 'column_name' )
o sys.fn_cdc_get_max_lsn
o sys.fn_cdc_get_min_lsn
o sys.fn_cdc_has_column_changed
o sys.fn_cdc_increment_lsn
o sys.fn_cdc_is_bit_set
o sys.fn_cdc_map_lsn_to_time
o sys.fn_cdc_map_time_to_lsn
Do the change tables keep growing?
No, there is an automatic cleanup process that occurs every three days (and this is configurable). For more intense environments you can leverage the manual method using the system stored procedure: sys.sp_cdc_cleanup_change_table. When you execute this system procedure you specify the low LSN and any change records occuring before this point are removed and the start_lsn is set to the low LSN you specified.
How do you leverage CDC in SSIS Packages?
Books Online in CTP5 (November) actually has a sample package in the topic 'change data capture in integration services' and I found this to be a good starting point to build from. For my CDC/SSIS demo here is the Control/Data Flow I am using:
1. Calculate Date Intervals (these will correspond to LSNs later) *also note that in both BOL and my own package we are using fixed intervals, in the real world this will be driven by a table solution which tells the SSIS package when the last successful execution occurs (starting point of next package iteration)
2. Check is any data is available in the selected date/time interval. This is important because the rest of the package will fail if no data is ready. BOL recommends performing Thead.Sleep/WAITFORs here. I am not for demo purposes but its not a bad idea.
3. Build the query via a SSIS variable *BOL states that SSIS packages cannot call the cdc.fn_cdc_getnetall functions and must use a wrapper. Whether or not we end up being forced to do this, it is a good design practice, below is my custom function that SSIS calls passing in the start/end datetime values to get the actual change data in the data flow step below.
4. Create a data flow task that executes the SSIS variable query (OLEDB source), and then splits the rows into via a conditional split based on the CDC_OPERATION column calculated in the function below.
4 steps to increase bandwidth performance for ASPX pages on IIS 6.0
---------------------------------------------------
http://www.codeproject.com/KB/aspnet/4stepsASPXIIS6.aspx
Friday, September 18, 2009
To see Tables Relations in Database
Select
object_name(rkeyid) Parent_Table,
object_name(fkeyid) Child_Table,
object_name(constid) FKey_Name,
c1.name FKey_Col,
c2.name Ref_KeyCol
From
sys.sysforeignkeys s
Inner join sys.syscolumns c1
on ( s.fkeyid = c1.id And s.fkey = c1.colid )
Inner join syscolumns c2
on ( s.rkeyid = c2.id And s.rkey = c2.colid )
Order by Parent_Table,Child_Table
DDL triggers and instead of DDL triggers
Much like regular DML triggers, DDL triggers fire in response to an event happening on the server. However, DDL triggers do not fire in response to UPDATE, INSERT, or DELETE statements on a table or view. Instead, they fire in response to Data Definition Language (DDL) statements that start with the keywords CREATE, ALTER, and DROP.
You can use DDL triggers to audit and regulate database operations. For instance, you can write a DDL trigger to prevent certain changes to your database schema, or maybe allow the change but record it in a log table for auditing purposes.
Certain system stored procedures that perform DDL-like operations can also fire DDL triggers. The CREATE TYPE statement and the sp_addtype stored procedure can both fire a DDL trigger. However, not all system stored procedures fire DDL triggers. The sp_rename stored procedure for instance does not fire any DDL triggers. You need to test your DDL triggers to determine their responses to system stored procedures.
DDL triggers can be server-scoped or database-scoped. A database-scoped DDL trigger is simply called a database trigger. The following example shows how a database trigger can be used to prevent any table in the current database from being modified or dropped. Keep in mind that DDL triggers fire only after the DDL statements that trigger them are run:
CREATE TRIGGER trigger1
ON DATABASEFOR
DROP_TABLE, ALTER_TABLE
AS PRINT 'You cannot drop or alter this table.'
ROLLBACK
You can temporarily disable a DDL trigger. Disabling a DDL trigger does not drop it. The trigger will still exists as an object; however, it will not be triggered by any of statements on which it was programmed. DDL triggers that are disabled can be re-enabled. Enabling a DDL trigger causes it to fire in the same way the trigger did when it was originally created.
DDL triggers do not fire in response to events that affect local or global temporary tables and stored procedures.
Some DDL statements, like CREATE DATABASE, cannot be used in DDL triggers. These statements are usually asynchronous, non-transacted statements
Thursday, September 17, 2009
Wednesday, September 16, 2009
Set conditional event handling of Control
protected void Page_Load(object sender, EventArgs e)
{
if (ClickStatus == false)
btn.Click += new EventHandler(btn_Click);
else
btn.Click += new EventHandler(btn_Click1);
}
protected void btn_Click(object sender, EventArgs e)
{
Response.Write("
hello with deligate one");
ClickStatus = true;
}
protected void btn_Click1(object sender, EventArgs e)
{
Response.Write("
hello with deligate two");
ClickStatus = false;
}