ASP.net- SQL Interview Questions With Answers

Embed Size (px)

Citation preview

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    1/27

    Dear Friends,

    Hi I am Raman Rattan Bhardwaj, this documents contains all the important questions thatusually asked during the Asp.Net,SQL SERVER Interview Questions, I had downloaded allthe material from the Internet from various websites and collected to form a single film, uwill find few repeated questions also, all the material are from the various websites, so Ihad just bind it into a single file. So for any mistake I am not responsible, this is just for

    the view purpose. My view was only to collect a material to a single file.

    Please, if u find any mistake in this file, please contact me to my email [email protected], so that I can able to correct it.

    ALL THE BEST

    Thanks

    Raman Rattan Bhardwaj.

    Contact me: 09958901108

    SQL SERVER Interview Questions

    1 General Questions of SQL SERVER... 22 Common Questions Asked. 83 Questions of SQL SERVER 2008 161) General Questions of SQL SERVER

    What is RDBMS?

    Relational Data Base Management Systems (RDBMS) are database management systems thatmaintain data records and indices in tables. Relationships may be created and maintainedacross and among the data and tables. In a relational database, relationships between dataitems are expressed by means of tables. Interdependencies among these tables are expressedby data values rather than by pointers. This allows a high degree of data independence. AnRDBMS has the capability to recombine the data items from different files, providing powerfultools for data usage. (Read More Here )

    What are the properties of the Relational tables?

    Relational tables have six properties: Values are atomic. Column values are of the same kind. Each row is unique. The sequence of columns is insignificant. The sequence of rows is insignificant. Each column must have a unique name.

    What is Normalization?Database normalization is a data design and organization process applied to datastructures based on rules that help building rlational databases. In relational databasedesign, the process of organizing data to minimize redundancy is called normalization.Normalization usually involves dividing a database into two or more tables and definingrelationships 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 thenpropagated through the rest of the database via the define relationships.

    What is Denormalization?

    Denormalization is the process of attempting to optimize the performance of a databaseby adding redundant data. It is sometimes necessary because current DBMSs implement

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    2/27

    the relational model poorly. A true relational DBMS would allow for a fully normalizeddatabase at the logical level, while providing physical storage of data that is tuned forhigh performance. Denormalization is a technique to move from higher to lower normalforms of database modeling in order to speed up database acces

    What are different normalization forms?

    1NF: Eliminate Repeating GroupsMake a separate table for each set of related attributes, and give each table a primarykey. Each field contains at most one value from its attribute domain.

    2NF: Eliminate Redundant DataIf an attribute depends on only part of a multivalued key, remove it to a separate table.

    3NF: Eliminate Columns Not Dependent On KeyIf attributes do not contribute to a description of the key, remove them to a separate

    table. All attributes must be directly dependent on the primary key. (Read More Here )

    BCNF: BoyceCodd Normal FormIf there are nontrivial dependencies between candidate key attributes, separate them outinto distinct tables.

    4NF: Isolate Independent Multiple RelationshipsNo table may contain two or more 1:n or n:m relationships that are not directly

    related.

    5NF: Isolate Semantically Related Multiple Relationships There may be practical constrains on information that justify separating logically related

    manytomany relationships.

    ONF: Optimal Normal FormA model limited to only simple (elemental) facts, as expressed in Object Role Model

    notation.

    DKNF: DomainKey Normal Form

    A model free from all modification anomalies is said to be in DKNF.

    Remember, these normalization guidelines are cumulative. For a database to be in 3NF, itmust first fulfill all the criteria of a 2NF and 1NF database.

    What is Stored Procedure?A stored procedure is a named group of SQL statements that have been previouslycreated and stored in the server database. Stored procedures accept input parameters sothat a single procedure can be used over the network by several clients using diferentinput data. And when the procedure is modified, all clients automatically get the newversion. Stored procedures reduce network traffic and improve performance. Storedprocedures can be used to help ensure the integrity of the database.

    e.g. sp_helpdb, sp_renamedb, sp_depends etc.

    What is Trigger?A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETEor UPDATE) occurs. Triggers are stored in and managed by the DBMS. Triggers areused to maintain the referential integrity of data by changing the data in asystematic fashion. A trigger cannot be called or executed; DBMS automatically firesthe trigger as a result of a data modification to the associated table. Triggers can beviewed as similar to stored procedures in that both consist of procedural logic that isstored at the databaselevel. Stored procedures, however, are not eventdrive and arenot attached to a specific table as triggers are. Stored procedures are explicitly

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    3/27

    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 withinitself, so when the trigger is fired because of data modification it can also cause anotherdata modification, thereby firing another trigger. A trigger that contains data modificationlogic within itself is called a nested trigger. (Read More Here )

    What is View?A simple view can be thought of as a subset of a table. It can be used for retrievingdata, as well as updating or deleting rows. Rows updated or deleted in the view areupdated or deleted in the table the view was created with. It should also be noted thatas data in the original table changes, so does data in the view, as views are the way tolook at part of the original table. The results of using a view are not permanently storedin the database. The data accessed through a view is actually constructed using standard TSQL select command and can come from one to many different base tables or evenother views.

    What is Index?An index is a physical structure containing pointers to the data. Indices are created in anexisting table to locate rows more quickly and efficiently. It is possible to create an indexon one or more columns of a table, and each index is given a name. The users cannot

    see the indexes; they are just used to speed up queries. Effective indexes are one of thebest ways to improve performance in a database application. A table scan happens whenthere is no index available to help a query. In a table scan SQL Server examines everyrow in the table to satisfy the query results. Table scans are sometimes unavoidable, buton large tables, scans have a terrific impact on performance.

    What is a Linked Server?Linked Servers is a concept in SQL Server by which we can add other SQL Server toa Group and query both the SQL Server dbs usig TSQL Statements. With a linkedserver, you can create very clean, easy to follow, SQL statements that allow remotedata to be retrieved, joined and combined with local data. Stored Proceduresp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server. (ReadMore Here )

    What is Cursor?

    Cursor is a database object used by applications to manipulate data in a set on a rowbyrow basis, instead of the typical SQL commands that operate on all the rows in the setat one time.

    In order to work with a cursor we need to perform some steps in the following order:1 Declare cursor

    Open cursor Fetch row from the cursor Process fetched row Close cursor Deallocate cursor (Read More Here )

    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, withoptions for specifying case sensitivity, accent marks, kana character types and

    character width. (Read More Here )

    What is Difference between Function and Stored Procedure?UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECTsection where as Stored procedures cannot be. UDFs that return tables can be treatedas another rowset. This can be used in JOINs with other tables. Inline UDF's can bethought of as views that take parameters and can be used in JOINs and other Rowsetoperations.

    What is subquery? Explain properties of subquery?

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    4/27

    Subqueries are often referred to as subselects, as they allow a SELECT statement tobe executed arbitrarily within the body of another SQL statement. A subquery isexecuted by enclosing it in a set of parentheses. Subqueries are generally used toreturn a single row as an atomic value, though they may be used to compare valuesagainst multiple rows with the IN keyword.

    A subquery is a SELECT statement that is nested within another TSQL statement. A

    subquery SELECT statement if executed independently of the TSQL statement, inwhich it is nested, will return a resultset. Meaning a subquery SELECT statement canstandalone and is not depended on the statement in which it is nested. A subquerySELECT statement can return any number of values, and can be found in, the columnlist of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses ofa TSQL 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.

    What are different Types of Join?

    Cross JoinA cross join that does not have a WHERE clause produces the Cartesian product ofthe tables involved in the join. The size of a Cartesian product result set is thenumber of rows in the first table multiplied by the number of rows in the seondtable. The common example is when company wants to combine each product with a

    pricing table to analyze each product at each price.

    Inner JoinA join that displays only the rows that have a match in both joined tables is knownas inner Join. This is the default type of join in the Query and View Designer.

    Outer JoinA join that includes rows even if they do not have related rows in the joined table isan Outer Join. You can create three different outer join to specify the unmatchedrows to be included:

    1 Left Outer Join:In Left Outer Join all rows in the firstnamed table i.e. "left" table, which appears leftmost inthe JOIN clause are included. Unmatched rows in the right table do not appear.

    Right Outer Join: In Right Outer Join all rows in the secondnamed table i.e."right" table, which appears rightmost in the JOIN clause are included. Unmatchedrows in the left table are not included.

    1 Full Outer Join: In Full Outer Join all rows in all joined tables are included, whetherthey are matched or not.

    Self Join This is a particular case when one table joins to itself, with one or two aliases to avoid

    confusion. A self join can be of any type, as long as the joined tables are the same. Aself join is rather unique in that it involves a relationship with only one table. Thecommon example is when company has a hierarchal reporting structure whereby onemember of staff reports to another. Self Join can be Outer Join or Inner Join

    What are primary keys and foreign keys?Primary keys are the unique identifiers for each row. They must contain unique values andcannot be null. Due to their importance in relational databases, Primary keys are themost fundamental of all keys and constraints. A table can have only one Primary key.

    Foreign keys are both a method of ensuring data integrity and a manifestation of therelationship between tables.

    What is User Defined Functions? What kind of UserDefined Functions can becreated?

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    5/27

    UserDefined Functions allow defining its own TSQL functions that can accept 0 or moreparameters and return a single scalar data value or a table data type.

    Different Kinds of UserDefined Functions created are:Scalar UserDefined FunctionA Scalar userdefined function returns one of the scalar data types. Text, ntext, image andtimestamp data types are not supported. These are the type of userdefined functions

    that most developers are used to in other programming languages. You pass in 0 tomany parameters and you get a return value.

    Inline TableValue UserDefined FunctionAn Inline TableValue userdefined function returns a table data type and is an exceptionalalternative to a view as the userdefined function can pass parameters into a TSQLselect command and in essence provide us with a parameterized, nonupdateable view ofthe underlying tables.

    Multistatement TableValue UserDefined FunctionA MultiStatement TableValue userdefined function returns a table and is also anexceptional alternative to a view as the function can support multiple TSQL statements tobuild the final result where the view is limited to a single SELECT statement. Also, theability to pass parameters into a TSQL select command or a group of them gives us thecapability to in essence create a paameterized, nonupdateable view of the data in the

    underlying tables. Within the create function command you must define the table structurethat is being returned. After creating this type of userdefined function, It can be used inthe FROM clause of a TSQL command unlike the behavior found when using a storedprocedure which can also return record sets. (Read Here For Example )

    What is Identity?Identity (or AutoNumber) is a column that automatically generates numeric values. A startand increment value can be set, but most DBA leave these at 1. A GUID column alsogenerates numbers; the value of this cannot be controlled. Identity/GUID columns do notneed to be indexed.

    What is DataWarehousing?

    1 Subjectoriented, meaning that the data in the database is organized so that all thedata elements relating to the same realworld event or object are linked together;

    Timevariant, meaning that the changes to the data in the database are tracked andrecorded so that reports can be produced showing changes ver time; Nonvolatile, meaning that data in the database is never overwritten or deleted,once committed, the data is static, readonly, but retained for future reporting. Integrated, meaning that the database contains data from most or all of anorganization's operational applications, and that this data is made consistent.

    2) Common Questions Asked

    Which TCP/IP port does SQL Server run on? How can it be changed?SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IPproperties > Port number, both on client and the server.

    What are the difference between clustered and a nonclustered index? (Read MoreHere )

    A clustered indexis a special type of index that reorders the way records in the table arephysically stored. Therefore table can have only one clustered index. The leaf nodes of aclustered index contain the data pages.

    A non clustered indexis a special type of index in which the logical order of the indexdoes not match the physical stored ordr of the rows on disk. The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain indexrows.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    6/27

    What are the different index configurations a table can have?A table can have one of the following index configurations:

    1 No indexes A clustered index A clustered index and many nonclustered indexes A nonclustered index

    Many nonclustered indexes

    What are different types 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 treateddifferently, it is called Kana sensitive.

    Width sensitivity A singlebyte character (halfwidth) and the same character representedas a doublebyte character (fullwidth) are treated differently than it is width sensitive.(Read More Here )

    What is OLTP (Online Transaction Processing)?

    In OLTP online transaction processing systems relational database design use thediscipline of data modeling and generally follow the odd rules of data normalization inorder to ensure absolute data integrity. Using these rules complex information is brokendown into its most simple structures (a table) where all of the individual atomic levelelements relate to each other and satisfy the normalization rules.

    What's the difference between a primary key and a unique key?Both primary key and unique key enforces uniqueness of the column on which theyare 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 isthat, primary key doesn't allow NULLs, but unique key allows one NULL only. (ReadMore Here )

    What is difference between DELETE & TRUNCATE commands?

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

    TRUNCATE1 TRUNCATE is faster and uses fewer system and transaction log resources thanDELETE.2 TRUNCATE removes the data by deallocating the data pages used to store the tables data,and only the page deallocations are recorded in the transaction log.

    TRUNCATE removes all rows from a table, but the table structure, its columns, constraints,indexes and so on, remains. The counter used by an identity for new rows is reset to theseed 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 cannot be rolled back. TRUNCATE is DDL Command. TRUNCATE Resets identity of the table

    DELETE

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    7/27

    1 DELETE removes rows one at a time and records an entry in the transaction log foreach deleted row. If you want to retain the identity counter, use DELETE instead. If you want to remove tabledefinition 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.

    DELETE is DML Command. DELETE does not reset identity of the table.

    When is the use of 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 toupdate the indexes to take these changes into account. UPDATE_STATISTICS updates theindexes on these tables accordingly.

    What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? They specify a search condition for a group or an aggregate. But the difference is that

    HAVING can be used only with the SELECT statement. HAVING is typically used in aGROUP 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 whereas

    WHERE Clause is applied to each row before hey are part of the GROUP BY function in aquery. (Read More Here )

    What are the properties and different Types of SubQueries?Properties of SubQuery

    1 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 an ORDERBY clause. A query can contain more than one subquery.

    Types of Subquery1 Singlerow subquery, where the subquery returns only one row. Multiplerow subquery, where the subquery returns multiple rows,. and Multiple column subquery, where the subquery returns multiple columns

    What is SQL Profiler?SQL Profiler is a graphical tool that allows system administrators to monitor events in aninstance of Microsoft SQL Server. You can capture and save data about each event to afile or SQL Server table to analyze later. For example, you can monitor a productionenvironment to see which stored procedures are hampering performances by executing tooslowly.

    Use SQL Profiler to monitor only the events in which you are interested. If traces are

    becoming too large, you can filter them based on the information you want, so that onlya subset of the event data is collected. Monitoring too many events adds overhead tothe server and the monitoring process and can cause the trace file or trace table o growvery large, especially when the monitoring process takes place over a long period oftime.

    What are the authentication modes in SQL Server? How can it be changed?Windows mode and Mixed Mode SQL & Windows. To change authentication mode in SQL Server click Start, Programs, Microsoft SQL Server

    and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    8/27

    Server program grou. Select the server then from the Tools menu select SQL ServerConfiguration Properties, and choose the Security page.

    Which command using Query Analyzer will give you the version of SQL server andoperating system?

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

    What is SQL Server Agent?SQL Server agent plays an important role in the daytoday tasks of a databaseadministrator (DBA). It is often overlooked as one of the main tools for SQL Servermanagement. Its purpose is to ease the implementation of tasks for the DBA, with itsfullfunction scheduling engine, which allows you to schedule your own jobs and scripts.(Read More Here )

    Can a stored procedure call itself or recursive stored procedure? How much levelSP nesting is possible?

    Yes. Because TransactSQL supports recursion, you can write stored procedures that callthemselves. Recursion can be defined as a method of problem solving wherein thesolution is arrived at by repetitively applying it to substs of the problem. A commonapplication of recursive logic is to perform numeric computations that lend themselves torepetitive evaluation by th 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 to32 levels.

    What is Log Shipping?Log shipping is the process of automating the backup of database and transaction log fileson a production SQL server, and then restoring them onto a standby server. EnterpriseEditions only supports log shipping. In log shipping the transactional log file from oneserver is automatically updated into the backup database on the other servr. If oneserver fails, the other server will have the same db and can be used this as the DisasterRecovery plan. The key feature of log shipping is that it will automatically backuptransaction logs throughout the day and automatically resore them on the standby serverat defined interval.

    Name 3 ways to get an accurate count of the number of records in a table?SELECT * FROM table1SELECT COUNT(*) FROM table1SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2

    What does it mean to have QUOTED_IDENTIFIER ON? What are the implications ofhaving it OFF?

    When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotationmarks, and literals must be delimited by single quotation marks. When SETQUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all TransactSQLrules for identifiers.

    What is the difference between a Local and a Global temporary table? A local temporary table exists only for the duration of a connection or, if defined inside a

    compound statement, for the duration of the compound statement.

    A global temporary table remains in the database permanently, but the rows exist onlywithin a given connection. When connection is closed, the data in the global temporarytable disappears. However, the table definition remains with the database for access whendatabase is opened next time.

    What is the STUFF function and how does it differ from the REPLACE function?STUFF function is used to overwrite existing characters. Using this syntax, STUFF(string_expression, start, length, replacement_characters), string_expression is the stringthat will have characters substituted, start is the starting position, length is the number

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    9/27

    of characters in the string that are substituted, and replacement_characters are the newcharacters interjected into the string. REPLACE function to replace existing characters ofall occurrences. Using the syntax REPLACE (string_expression, search_string,replacement_string), where every incidence of search_string found in the string_expressionwill be replaced with replacement_string.

    What is PRIMARY KEY?

    A PRIMARY KEY constraint is a unique identifier for a row within a database table. Everytable should have a primary key constraint to uniquely identify each row and only oneprimary key constraint can be creaed for each table. The primary key constraints areused to enforce entity integrity.

    What is UNIQUE KEY constraint?A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so noduplicate values are entered. The unique key constraints are used to enforce entityintegrity as the primary key constraints.

    What is FOREIGN KEY?A FOREIGN KEY constraint prevents any actions that would destroy links between tableswith the corresponding data values. A foreign key in one table points to a primary key inanother table. Foreign keys prevent actions that would leave rows with foreign key valueswhen there are no primary keys with that value. The foreign key constraints are used to

    enforce referential integrity.

    What is CHECK Constraint?A CHECK constraint is used to limit the values that can be placed in a column. Thecheck constraints are used to enforce domain integrity.

    What is NOT NULL Constraint?A NOT NULL constraint enforces that the column will not accept null values. The notnull constraints are used to enforce domain integrity, as the check constraints.(Read More Here )

    How to get @@ERROR and @@ROWCOUNT at the same time?If @@Rowcount is checked after Error checking statement then it will have 0 as the valueof @@Recordcount as it would have been reset. And if @@Recordcount is checked before

    the errorchecking statement then @@Error would get reset. To get @@error and@@rowcount at the same time do both in same statement and store them in localvariable. SELECT @RC = @@ROWCOUNT, @ER = @@ERROR

    What is a Scheduled Jobs or What is a Scheduled Tasks?Scheduled tasks let user automate processes that run on regular or predictable cycles.User can schedule administrative tasks, such as cube processing, to run during times ofslow business activity. User can also determine the order in which tasks run by creating job steps within a SQL Server Agent job. E.g. back up database, Update Stats of Tables. Job steps give user control over flow of execution. If one job fails, user can configureSQL Server Agent to continue to run the remaining tasks or to stop execution.

    What are the advantages of using Stored Procedures?1 Stored procedure can reduced network traffic and latency, boosting applicationperformance.

    Stored procedure execution plans can be reused, staying cached in SQL Server'smemory, reducing server overhead. Stored procedures help promote code reuse. Stored procedures can encapsulate logic. You can change stored procedure codewithout affecting clients. Stored procedures provide better security to your data.

    What is a table called, if it has neither Cluster nor Noncluster Index? What is itused for?

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    10/27

    Unindexed table or Heap. Microsoft Press Books and Book on Line (BOL) refers it as Heap.A heap is a table that does not have a clustered index and, therefore, the pages are notlinked by pointers. The IAM pages are the only structures that link the pages in a tabletogether. Unindexed tables are good for fast storing of data. Many times it is better todrop all indexes from table and then do bulk of inserts and to restore those indexesafter that.

    Can SQL Servers linked to other servers like Oracle?SQL Server can be linked to any server provided it has OLEDB provider from Microsoft toallow a link. E.g. Oracle has an OLEDB provider for oracle that Microsoft provides to addit as linked server to SQL Server group .

    What is BCP? When does it used?BulkCopy is a tool used to copy huge amount of data from tables and views. BCP doesnot copy the structures same as source to destination. BULK INSERT command helps toimport a data file into a database table or view in a userspecified format.

    What command do we use to rename a db, a table and a column?To rename dbsp_renamedb oldname , newnameIf someone is using db it will not accept sp_renmaedb. In that case first bring db tosingle user using sp_dboptions. Use sp_renamedb to rename database. Use sp_dboptions

    to bring database to multi user mode.

    E.g.USE master;GOEXEC sp_dboption AdventureWorks, 'Single User', TrueGOEXEC sp_renamedb 'AdventureWorks', 'AdventureWorks_New'GOEXEC sp_dboption AdventureWorks, 'Single User', FalseGO

    To rename TableWe can change the table name using sp_rename as follows,

    sp_rename oldTableName newTableName

    E.g.SP_RENAME Table_First, Table_Last GO

    To rename Column The script for renaming any column :sp_rename TableName.[OldcolumnName], NewColumnName, ColumnE.g.

    sp_RENAME Table_First.Name, NameChange , COLUMN GO

    What are sp_configure commands and set commands?Use sp_configure to display or change serverlevel settings. To change databaselevelsettings, use ALTER DATABASE. To change settings that affect only the current usersession, use the SET statement. E.g.

    sp_CONFIGURE show advanced, 0 GO RECONFIGURE GO sp_CONFIGURE GO

    You can run following command and check advance global configuration settings.

    sp_CONFIGURE show advanced, 1 GO RECONFIGURE GO sp_CONFIGURE GO

    (Read More Here )

    How to implement onetoone, onetomany and manytomany relationships whiledesigning tables?

    OnetoOne relationship can be implemented as a single table and rarely as two tables withprimary and foreign key relationships. OnetoMany relationships are implemented by splittingthe data into two tables with primary key and foreign key relationships.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    11/27

    ManytoMany relationships are implemented using a junction table with the keys from boththe tables forming the composite primary key f the junction table.

    What is an execution plan? When would you use it? How would you view theexecution plan?

    An execution plan is basically a road map that graphically or textually shows the dataretrieval methods chosen by the SQL Servr query optimizer for a stored procedure or adhoc

    query and is a very useful tool for a developer to understand the performance characteristicsof a query or stored procedur since the plan is the one that SQL Server will place in itscache and use to execute the stored procedure or query. From within Query Analyzer is anoption called "Show Execution Plan" (located on the Query dropdown menu). If this option isturned on it will display query execution plan in separate window when query is ran again.

    3) Questions of SQL SERVER 2008

    What are the basic functions for master, msdb, model, tempdb and resourcedatabases?

    The master database holds information for all databases located on the SQL Serverinstance and is theglue that holds the enginetogether. Because SQL Server cannot startwithout a functioning masterdatabase, you must administer this database with care.

    The msdb database stores information regarding database backups, SQL Agent information,DTS packages, SQL Server jobs, and some replication information such as for log shipping.

    The tempdb holds temporary objects such as global and local temporary tables andstored procedures.

    The model is essentially a template database used in the creation of any new userdatabase created in the instance.

    The resoure Database is a readonly database that contains all the system objects thatare included with SQL Server. SQL Server system objects, such as sys.objects, arephysically persisted in the Resource database, but they logically appear in the sys schemaof every database. The Resource database does not contain user data or user metadata.

    What is Service Broker?Service Broker is a messagequeuing technology in SQL Server that allows developers tointegrate SQL Server fully into distributed applications. Service Broker is feature whichprovides facility to SQL Server to send an asynchronous, transactional message. it allows adatabase to send a message to another database without waiting for the response, so theapplication will continue to function if the remote database is temporarily unavailable. (ReadMore Here )

    Where SQL server user names and passwords are stored in SQL server? They get stored in System Catalog Views sys.server_principals and sys.sql_logins.

    What is Policy Management?Policy Management in SQL SERVER 2008 allows you to define and enforce policies forconfiguring and managing SQL Server across te enterprise. PolicyBased Management is

    configured in SQL Server Management Studio (SSMS). Navigate to the Object Explorerand expand the Management node and the Policy Management node; you will see thePolicies, Conditions, and Facets nodes. (Read More Here )

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    12/27

    What is Replication and Database Mirroring?Database mirroring can be used with replication to provide availability for the publicationdatabase. Database mirroring involves two copies of a single database that typically resideon different computers. At any given time, only one copy of the database is currentlyavailable to clients which are known as the principal database. Updates made by clientsto the principal database are applied on the other copy of the database, known as themirror database. Mirroring involves applying the transaction log from every insertion,

    update, or deletion made on the principal database onto the mirror database.

    What are Sparse Columns?A sparse column is another tool used to reduce the amount of physical storage used in adatabase. They are the ordinary columns that have an optimized storage for null values.Sparse columns reduce the space requirements for null values at the cost of moreoverhead to retrieve nonnull values. (Read More Here )

    What does TOP Operator Do? The TOP operator is used to specify the number of rows to be returned by a query. The TOP operator has new addition in SQL SERVER 2008 that it accepts variables as well asliteral values and can be used with NSERT, UPDATE, and DELETES statements.

    What is CTE?CTE is an abbreviation Common Table Expression. A Common Table Expression (CTE) is an

    expression that can be thought of as a temporary result set which is defined within theexecution of a single SQL statemnt. A CTE is similar to a derived table in that it is notstored as an object and lasts only for the duration of the query. (Read More Here )

    What is MERGE Statement? MERGE is a new feature that provides an efficient way to perform multiple DMLoperations. In previous versions of SQL Server, we had to write separate statementsto INSERT, UPDATE, or DELETE data based on certain conditions, but now, usingMERGE statement we can include the logic of such data modifications in onestatement that even checks when the data is mtched then just update it and whenunmatched then insert it. One of the most important advantages of MERGE statementis all the data is read and processed only once. (Read More Here )

    What is Filtered Index?

    Filtered Index is used to index a portion of rows in a table that means it applies filteron INDEX which improves query performnce, reduce index maintenance costs, andreduce index storage costs compared with fulltable indexes. When we see an Indexcreated with some where clause then that is actually a FILTERED INDEX.

    Which are new data types introduced in SQL SERVER 2008?The GEOMETRY Type: The GEOMETRY data type is a system .NET common languageruntime (CLR) data type in SQL Server. This type represents data in a twodimensionalEuclidean coordinate system.

    The GEOGRAPHY Type: The GEOGRAPHY datatypes functions are the same as withGEOMETRY. The difference between the two is that when you specify GEOGRAPHY, youare usually specifying points in terms of latitude and longitude.

    New Date and Time Datatypes: SQL Server 2008 introduces four new datatypes relatedto date and time: DATE, TIME, DATETIMEOFFSET, and DATETIME2.

    1 DATE: The new DATE type just stores the date itself. It is based on the Gregoriancalendar and

    handles years from 1 to 9999. TIME: The new TIME (n) type stores time with a range of 00:00:00.0000000 through23:59:59.9999999. The precision is allowed with this type. TIME supports seconds downto 100 nanoseconds. The n in TIME (n) defines this level of fractional secondprecision, from 0 to 7 digits of precision.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    13/27

    1 The DATETIMEOFFSET Type: DATETIMEOFFSET (n) is the timezoneaware version ofa datetime datatype. The name will appear less odd when you consider what it really is: adate + a time + a timezone offset. The offset is based on how far behind or ahead youare from Coordinated Universal Time (UTC) time.

    1 The DATETIME2 Type: It is an extension of the datetime type in earlier versions of SQLServer. This new datatype has a date range covering dates from January 1 of year 1through December 31 of year 9999. This is a definite improvement over the 1753 lowerboundary of the datetime datatype. DATETIME2 not only includes the larger date range, butalso has a timestamp and the same fractional precision that TIME type provides

    What are the Advantages of using CTE?

    1 Using CTE improves the readability and makes maintenance of complex queries easy.

    The query can be divided into separate, simple, logical building blocks which can bethen used to build more complex CTEs until final result set is generated. CTE can be defined in functions, stored procedures, triggers or even views. After a CTE is defined, it can be used as a Table or a View and can SELECT,INSERT, UPDATE or DELETE Data.

    How can we rewrite subqueries into simple select statements or with joins? Yes we can write using Common Table Expression (CTE). A Common Table Expression

    (CTE) is an expression that can be thought of as a temporary result set which is definedwithin the execution of a single SQL statemnt. A CTE is similar to a derived table in thatit is not stored as an object and lasts only for the duration of the query.

    E.g.USE AdventureWorks GO WITH EmployeeDepartment_CTE AS ( SELECTEmployeeID,DepartmentID,ShiftID FROM HumanResources.EmployeeDepartmentHistory

    ) SELECT ecte.EmployeeId,ed.DepartmentID, ed.Name,ecte.ShiftID FROMHumanResources.Department ed INNER JOIN EmployeeDepartment_CTE ecte ONecte.DepartmentID = ed.DepartmentID GO

    What is CLR?In SQL Server 2008, SQL Server objects such as userdefined functions can be createdusing such CLR languages. This CLR language support extends not only to userdefinedfunctions, but also to stored procedures and triggers. You can develop such CLR addonsto SQL Server using Visual Studio 2008. (Read More Here )

    What are synonyms?Synonyms give you the ability to provide alternate names for database objects. Youcan alias object names; for example, using the Employee table as Emp. You can alsoshorten names. This is especially useful when dealing with three and four part names;

    for example, shortening server.database.owner.object to object. (Read More Here )

    What is LINQ?Language Integrated Query (LINQ) adds the ability to query objects using .NET languages. The LINQ to SQL object/relational mapping (O/RM) framework provides the following basicfeatures:

    1 Tools to create classes (usually called entities) mapped to database tables Compatibility with LINQs standard query operations

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    14/27

    The DataContext class, with features such as entity record monitoring, automatic SQLstatement generation, record concurrency detection, and much more .

    ASP.NET Interview Questions

    01. What is the CLR?Ans : CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory)any .NET program can take advantage of, regardless of programming language. Many .NET frameworkclasses Development, debugging, and profiling tools Execution and code management IL-to-nativetranslators and optimizers What this means is that in the .NET world, different programming

    languages will be more equal in capability than they have ever been before, although clearly not alllanguages will support all CLR services.02. What is the CTS?Ans : CTS = Common Type System. This is the range of types that the .NET runtime understands, andtherefore that .NET applications can use. However note that not all .NET languages will support all thetypes in the CTS. The CTS is a superset of the CLS.03. What is the CLS?Ans : CLS = Common Language Specification. This is a subset of the CTS which all .NET languages areexpected to support. The idea is that any program which uses CLS-compliant types can interoperatewith any .NET program written in any language.In theory this allows very tight interop between different .NET languages - for example allowing a C#class to inherit from a VB class.04. What is IL?Ans : IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL(Common Intermediate Language). All .NET source code (of any language) is compiled to IL. The IL isthen converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.05. What does 'managed' mean in the .NET context?Ans : The term 'managed' is the cause of much confusion. It is used in various places within .NET,meaning slightly different things.Managed code: The .NET framework provides several core run-timeservices to the programs that run within it - for exampleexception handling and security. For these services to work, the code must provide a minimum level of

    information to the runtime.Such code is called managed code. All C# and Visual Basic.NET code is managed by default. VS7 C++code is not managed by default, but the compiler can produce managed code by specifying acommand-line switch (/com+).Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector.C# and VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when usingthe /com+ switch, but it can be marked as managed using the __gc keyword.Managed classes: This isusually referred to in the context of Managed Extensions (ME) for C++. When using ME C++, a classcan be marked with the __gc keyword. As the name suggests, this means that the memory forinstances of the class is managed by the garbage collector, but it also means more than that. Theclass becomes a fully paid-up member of the .NET community with the benefits and restrictions thatbrings. An example of a benefit is proper interop with classes written in other languages - forexample, a managed C++ class can inherit from a VB class. An example of a restriction is that amanaged class can only inherit from one base class.06. What is reflection?Ans : All .NET compilers produce metadata about the types defined in the modules they produce. Thismetadata is packaged along with the module (modules in turn are packaged together in assemblies),and can be accessed by a mechanism called reflection. The System.Reflection namespace containsclasses that can be used to interrogate the types for a module/assembly.Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access typelibrary data in COM, and it is used for similar purposes - e.g. determining data type sizes formarshaling data across context/process/machine boundaries.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    15/27

    Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember ) , oreven create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

    07. What is the difference between Finalize and Dispose (Garbage collection) ?Ans : Class instances often encapsulate control over resources that are not managed by the runtime,such as window handles (HWND), database connections, and so on. Therefore, you should provideboth an explicit and an implicit way to free those resources. Provide implicit control by implementing

    the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions forC++). The garbage collector calls this method at some point after there are no longer any validreferences to the object. In some cases, you might want to provide programmers using an object withthe ability to explicitly release these external resources before the garbage collector frees the object.If an external resource is scarce or expensive, better performance can be achieved if the programmerexplicitly releases resources when they are no longer being used. To provide explicit control,implement the Dispose method provided by the IDisposable Interface. The consumer of the objectshould call this method when it is done using the object.Dispose can be called even if other references to the object are alive. Note that even when you

    provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalizemethod. Finalize provides a backup to prevent resources frompermanently leaking if the programmer fails to call Dispose.08. What is Partial Assembly References?

    Ans : Full Assembly reference: A full assembly reference includes the assembly's text name, version,culture, and public key token (if the assembly has a strong name). A full assembly reference isrequired if you reference any assembly that is part of the common language runtime or any assemblylocated in the global assembly cache.09. Changes to which portion of version number indicates an incompatible change?Ans : Major or minor. Changes to the major or minor portion of the version number indicate anincompatible change. Under this convention then, version 2.0.0.0 would be considered incompatiblewith version 1.0.0.0. Examples of an incompatible change would be a change to the types of somemethod parameters or the removal of a type or method altogether. Build. The Build number is typicallyused to distinguish between daily builds or smaller compatible releases. Revision. Changes to therevision number are typically reserved for an incremental build needed to fix a particular bug. You'llsometimes hear this referred to as the "emergency bug fix" number in that the revision is what is oftenchanged when a fix to a specific bug is shipped to a customer.

    10. How to set the debug mode?

    Debug Mode for ASP.NET applications - To set ASP.NET appplication in debugging mode, edit theapplication's web.config and assign the "debug" attribute in < compilation > section to "true" as showbelow:< configuration >< system.web >

    < compilation defaultLanguage="vb" debug="true" / >.........< / configuration >

    This case-sensitive attribute 'debug tells ASP.NET to generate symbols for dynamically generated files

    and enables thedebugger to attach to the ASP.NET application. ASP.NET will detect this change automatically, withoutthe need to restart the server. Debug Mode for ASP.NET Webservices - Debugging an XML Web service

    created with ASP.NET is similar to the debugging an ASP.NET Web application.

    11. What is managed and unmanaged code?

    Ans : The .NET framework provides several core run-time services to the programs that run within it -for example exception handling and security. For these services to work, the code must provide aminimum level of information to the runtime. i.e., code executing under the control of the CLR iscalled managed code. For example, any code written in C# or Visual Basic .NET is managed code.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    16/27

    Code that runs outside the CLR is referred to as "unmanaged code." COM components, ActiveXcomponents, and Win32 API functions are examples of unmanaged code.

    12. Describe the advantages of writing a managed code application instead of unmanagedone. What's involved in certain piece of code being managed?

    "Advantage includes automatic garbage collection,memory management,security,typechecking,versioning

    Managed code is compiled for the .NET run-time environment. It runs in the Common LanguageRuntime (CLR), which is the heart of the .NET Framework. The CLR provides services such as security,

    memory management, and cross-language integration. Managed applications written to takeadvantage of the features of the CLR perform more efficiently and safely, and take better advantageof developers existing expertise in languages that support the .NET Framework.

    Unmanaged code includes all code written before the .NET Framework was introducedthis includescode written to use COM, native Win32, and Visual Basic 6. Because it does not run inside the .NETenvironment, unmanaged code cannot make use of any .NET managed facilities."

    13. What is Boxing and UnBoxing?Ans : Boxing is implicit conversion of ValueTypes to Reference Types (Object). UnBoxing is explicitconversion of Reference Types (Object) to its equivalent ValueTypes. It requires type-casting.

    14. What is the sequence of operation takes place when a page is loaded?BeginTranaction - only if the request is transactedInit - every time a page is processedLoadViewState - Only on postbackProcessPostData1 - Only on postbackLoad - every timeProcessData2 - Only on PostbackRaiseChangedEvent - Only on PostbackRaisePostBackEvent - Only on PostbackPreRender - everytimeBuildTraceTree - only if tracing is enabledSaveViewState - every timeRender - EverytimeEnd Transaction - only if the request is transactedTrace.EndRequest - only when tracing is enabled

    UnloadRecursive - Every request

    15. What are the different types of assemblies available and their purpose?Ans : Private, Public/shared and Satellite Assemblies.

    Private Assemblies : Assembly used within an application is known as private assemblies.

    Public/shared Assemblies : Assembly which can be shared across applicaiton is known as sharedassemblies. Strong Name has to be created to create a shared assembly. This can be done usingSN.EXE. The same has to be registered using GACUtil.exe (Global Assembly Cache).

    Satellite Assemblies : These assemblies contain resource files pertaining to a locale

    (Culture+Language). These assemblies are used in deploying an Gloabl applicaiton for differentlanguages.

    16. What is the difference between Server.Transfer and Response.Redirect? Why would Ichoose one over the other? Server.Transfer() : client is shown as it is on the requesting page only,but the all the content is of the requested page. Data can be persist accros the pages usingContext.Item collection, which is one of the best way to transfer data from one page to another

    keeping the page state alive.

    Response.Dedirect() :client know the physical location (page name and query string as well).

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    17/27

    Context.Items loses the persisitance when nevigate to destination page. In earlier versions of IIS, ifwe wanted to send a user to a new Web page, the only option we had was Response.Redirect. Whilethis method does accomplish our goal, it has several important drawbacks. The biggest problem isthat this method causes each page to be treated as a separate transaction. Besides making it difficultto maintain your transactional integrity, Response.Redirect introduces some additional headaches.First, it prevents good encapsulation of code. Second, you lose access to all of the properties in theRequest object. Sure, there are workarounds, but they're difficult. Finally, Response.Redirect

    necessitates a round trip to the client, which, on high-volume sites, causes 7scalability problems. Asyou might suspect, Server.Transfer fixes all of these problems. It does this by performing the transferon the server without requiring a roundtrip to the client.

    17.Describe the role ofinetinfo.exe, aspnet_isapi.dlland aspnet_wp.exe in the page loadingprocess ?

    Ans : inetinfo.exe is the Microsoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filteraspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe.

    18. Where do you store the information about the users locale?Ans : System.Web.UI.Page.Culture

    19. Describe the difference between inline and code behind.Ans : Inline code written along side the html in a page. Code-behind is code written in a separate fileand referenced by the .aspx page.

    20. What is different b/w webconfig.xml & Machineconfig.xmlWeb.config & machine.config both are configuration files.Web.config contains settings specific to anapplication where as machine.config contains settings to a computer. The Configuration system firstsearches settings in machine.config file & then looks in application configuration files.Web.config, canappear in multiple directories on an ASP.NET Web application server. Each Web.config file appliesconfiguration settings to its own directory and all child directories below it. There is onlyMachine.config file on a web server.

    If I'm developing an application that must accomodate multiple security levels though secure login andmy ASP.NET web appplication is spanned across three web-servers (using round-robbin load

    balancing) what would be the best approach to maintain login-in state for the users?Use the state server or store the state in the database. This can be easily done through simple settingchange in the web.config.

    You can specify mode as stateserver or sqlserver.

    Where would you use an iHTTPModule, and what are the limitations of any approach you might take inimplementing one"One of ASP.NET's most useful features is the extensibility of the HTTP pipeline, the path that data

    takes between client and server. You can use them to extend your ASP.NET applications by addingpre- and post-processing to each HTTP request coming into your application. For example, if youwanted custom authentication facilities for your application, the best technique would be to interceptthe request when it comes in and process the request in a custom HTTP module.

    21. How is the DLL Hell problem solved in .NET?Ans : Assembly versioning allows the application to specify not only the library it needs to run (whichwas available under Win32), but also the version of the assembly.

    22. What are the ways to deploy an assembly?Ans : An MSI installer, a CAB archive, and XCOPY command.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    18/27

    23. What is a satellite assembly?Ans : When you write a multilingual or multi-cultural application in .NET, and want to distribute thecore application separately from the localized modules, the localized assemblies that modify the coreapplication are called satellite assemblies.

    24. What namespaces are necessary to create a localized application?

    Ans : System.Globalization and System.Resources.

    25. What is the smallest unit of execution in .NET?Ans : an Assembly.

    26. When should you call the garbage collector in .NET?Ans : As a good rule, you should not call the garbage collector. However, you could call the garbagecollector when you are done using a large object (or set of objects) to force the garbage collector todispose of those very large objects from memory. However, this is usually not a good practice.

    27. How do you convert a value-type to a reference-type?Ans : Use Boxing.

    28. What happens in memory when you Box and Unbox a value-type?Ans : Boxing converts a value-type to a reference-type, thus storing the object on the heap.Unboxing converts a reference-type to a value-type, thus storing the value on the stack

    29. Describe the difference between a Thread and a Process?

    Ans : A Process is an instance of an running application. And a thread is the Execution stream of theProcess. A process can have multiple Thread.

    When a process starts a specific memory area is allocated to it. When there is multiple thread in aprocess, each thread gets a memory for storing the variables in it and plus they can access to theglobal variables which is common for all the thread. Eg.A Microsoft Word is a Application. When youopen a word file,an instance of the Word starts and a process is allocated to this instance which hasone thread.

    30. What is the difference between an EXE and a DLL?Ans : You can create an objects of Dll but not of the EXE.Dll is an In-Process Component whereas EXE is an OUt-Process Component.Exe is for single usewhereas you can use Dll for multiple use.Exe can be started as standalone where dll cannot be.

    31. What is strong-typing versus weak-typing? Which is preferred? Why? Ans : Strong typingimplies that the types of variables involved in operations are associated to the variable, checked atcompile-time, and require explicit conversion; weak typing implies that they are associated to thevalue, checked at run-time, and are implicitly converted as required. (Which is preferred is adisputable point, but I personally prefer strong typing because I like my errors to be found as soon aspossible.)

    32. What is the GAC? What problem does it solve?Each computer where the common language runtime is installed has a machine-wide code cache

    called the global assembly cache. The global assembly cache stores assemblies that are to be sharedby several applications on the computer. This area is typically the folder under windows or winnt in themachine.

    All the assemblies that need to be shared across applications need to be done through the Globalassembly Cache only. However it is not necessary to install assemblies into the global assembly cacheto make them accessible to COM interop or unmanaged code.

    There are several ways to deploy an assembly into the global assembly cache: Use an installer designed to work with the global assembly cache. This is the preferred option forinstalling assemblies into the global assembly cache.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    19/27

    Use a developer tool called the Global Assembly Cache tool (Gacutil.exe), provided by the .NETFramework SDK. Use Windows Explorer to drag assemblies into the cache.

    GAC solves the problem of DLL Hell and DLL versioning. Unlike earlier situations, GAC can hold twoassemblies of the same name but different version. This ensures that the applications which access aparticular assembly continue to access the same assembly even if another version of that assembly is

    installed on that machine.33. What is an Asssembly Qualified Name? Is it a filename? How is it different?

    An assembly qualified name isn't the filename of the assembly; it's the internal name of the assemblycombined with the assembly version, culture, and public key, thus making it unique.

    e.g. (""System.Xml.XmlDocument, System.Xml, Version=1.0.3300.0, Culture=neutral,PublicKeyToken=b77a5c561934e089"")

    34. How is a strongly-named assembly different from one that isnt strongly-named?

    Strong names are used to enable the stricter naming requirements associated with shared assemblies.These strong names are created by a .NET utility sn.exe

    Strong names have three goals: Name uniqueness. Shared assemblies must have names that are globally unique. Prevent name spoofing. Developers don't want someone else releasing a subsequent version of oneof your assemblies and falsely claim it came from you, either by accident or intentionally. Provide identity on reference. When resolving a reference to an assembly, strong names are used toguarantee the assembly that is loaded came from the expected publisher.

    Strong names are implemented using standard public key cryptography. In general, the process worksas follows: The author of an assembly generates a key pair (or uses an existing one), signs the filecontaining the manifest with the private key, and makes the public key available to callers. Whenreferences are made to the assembly, the caller records the public key corresponding to the privatekey used to generate the strong name.

    Weak named assemblies are not suitable to be added in GAC and shared. It is essential for anassembly to be strong named.

    Strong naming prevents tampering and enables assemblies to be placed in the GAC alongside otherassemblies of the same name

    35. Explain the importance and use of each, Version, Culture and PublicKeyToken for anassembly.This three alongwith name of the assembly provide a strong name or fully qualified name to theassembly. When a assebly is referenced with all three.

    PublicKeyToken: Each assembly can have a public key embedded in its manifest that identifies the

    developer. This ensures that once the assembly ships, no one can modify the code or other resourcescontained in the assembly.

    Culture: Specifies which culture the assembly supportsVersion: The version number of the assembly.It is of the following form major.minor.build.revision.

    Explain the differences between public, protected, private and internal.

    These all are access modifier and they governs the access level. They can be applied to class,methods, fields.

    Public: Allows class, methods, fields to be accessible from anywhere i.e. within and outside anassembly.

    Private: When applied to field and method allows to be accessible within a class.

    Protected: Similar to private but can be accessed by members of derived class also.

    Internal: They are public within the assembly i.e. they can be accessed by anyone within an assemblybut outside assembly they are not visible.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    20/27

    36. What is difference between MetaData and Manifest?Metadata and Manifest forms an integral part of an assembly( dll / exe ) in .net framework . Out ofwhich Metadata is a mandatory component , which as the name suggests gives the details aboutvarious components of IL code viz : Methods , properties , fields , class etc.

    Essentially Metadata maintains details in form of tables like Methods Metadata tables , PropertiesMetadata tables , which maintains the list of given type and other details like access specifier , return

    type etc.Now Manifest is a part of metadata only , fully called as manifest metadata tables , it contains thedetails of the references needed by the assembly of any other external assembly / type , it could be acustom assembly or standard System namespace .

    Now for an assembly that can independently exists and used in the .Net world both the things( Metadata with Manifest ) are mandatory , so that it can be fully described assembly and can beported anywhere without any system dependency . Essentially .Net framework can read all assemblyrelated information from assembly itself at runtime .

    But for .Net modules , that cant be used independently , until they are being packaged as a part of anassembly , they dont contain Manifest but their complete structure is defined by their respectivemetadata .

    Ultimately . .Net modules use Manifest Metadata tables of parent assembly which contain them .

    37. How do assemblies find each other? By searching directory paths. There are several factorswhich can affect the path (such as the AppDomain host, and application configuration files), but forprivate assemblies the search path is normally the application's directory and its sub-directories. Forshared assemblies, the search path is normally same as the private assembly path plus the sharedassembly cache.38. How does assembly versioning work? Each assembly has a version number called thecompatibility version. Also each reference to an assembly (from another assembly) includes both the

    name and version of the referenced assembly.The version number has four numeric parts (e.g.5.5.2.33). Assemblies with either of the first two parts different are normally viewed as incompatible.If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybecompatible'. If only the fourth part is different, the assemblies are deemed compatible. However, thisis just the default guideline - it is the version policy that decides to what extent these rules areenforced. The version policy can be specified via the application configuration file.

    38. What is garbage collection? Garbage collection is a system whereby a run-time componenttakes responsibility for managing the lifetime of objects and the heap memory that they occupy. Thisconcept is not new to .NET - Java and many other languages/runtimes have used garbage collectionfor some time.40. Why doesn't the .NET runtime offer deterministic destruction?Because of the garbage collection algorithm. The .NET garbage collector works by periodically runningthrough a list of all the objects that are currently being referenced by an application. All the objectsthat it doesn't find during this search are ready to be destroyed and the memory reclaimed. Theimplication of this algorithm is that the runtime doesn't get notified immediately when the finalreference on an object goes away - it only finds out during the next sweep of the heap.Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely aspossible. Normally heap exhaustion is the trigger for a collection sweep.

    41. Is the lack of deterministic destruction in .NET a problem?It's certainly an issue that affects component design. If you have objects that maintain expensive orscarce resources (e.g. database locks), you need to provide some way for the client to tell the objectto release the resource when it is done. Microsoft recommend that you provide a method calledDispose() for this purpose. However, this causes problems for distributed objects - in a distributedsystem who calls the Dispose() method? Some form of reference-counting or ownership-managementmechanism is needed to handle distributed objects - unfortunately the runtime offers no help withthis.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    21/27

    42. What is the use of JIT ? JIT (Just - In - Time) is a compiler which converts MSIL code to

    Because the common language runtime supplies a JIT compiler for each supported CPU architecture,developers can write a set of MSIL that can be JIT-compiled and run on computers with differentarchitectures. However, your managed code will run only on a specific operating system if it callsplatform-specific native APIs, or a platform-specific class library.

    JIT compilation takes into account the fact that some code might never get called during execution.

    Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to nativecode, it converts the MSIL as needed during execution and stores the resulting native code so that it isaccessible for subsequent calls. The loader creates and attaches a stub to each of a type's methodswhen the type is loaded. On the initial call to the method, the stub passes control to the JIT compiler,which converts the MSIL for that method into native code and modifies the stub to direct execution tothe location of the native code. Subsequent calls of the JIT-compiled method proceed directly to thenative code that was previously generated, reducing the time it takes to JIT-compile and run the code.

    43.What is delay signing?

    Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just thepublic key. This allows the assembly to be signed with the private key at a later stage, when thedevelopment process is complete and the component or assembly is ready to be deployed. Thisprocess enables developers to work with shared assemblies as ifthey were strongly named, and itsecures the private key of the signature from being accessed at different stages of development.

    44. Whats the difference between Response.Write() and Response.Output.Write()?Ans : Response.Output.Write() allows you to write formatted output.

    45. When during the page processing cycle is ViewState available?Ans : After the Init() and before the Page_Load(), or OnLoad() for a control.

    46. Whats a bubbled event?Ans : When you have a complex control, like DataGrid, writing an event processing routine for eachobject (cell, button, row, etc.) is quite tedious. The controls can bubble up their event handlers,allowing the main DataGrid event handler to take care of its constituents.

    47. What data types do the RangeValidator control support?Ans : Integer, String, and Date.

    48. Explain the differences between Server-side and Client-side code?Ans : Server-side code executes on the server. Client-side code executes in the client's browser.

    49. What type of code (server or client) is found in a Code-Behind class?Ans : The answer is server-side code since code-behind is executed on the server. However, duringthe code-behind's execution on the server, it can render client-side code such as JavaScript tobe processed in the clients browser. But just to be clear, code-behind executes on the server, thusmaking it server-side code.

    50. Should user input data validation occur server-side or client-side? Why?Ans : All user input data validation should occur on the server at a minimum. Additionally, client-sidevalidation can be performed where deemed appropriate and feasable to provide a richer, moreresponsive experience for the user.

    51. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?Valid answers are: A DataSet can represent an entire relational database in memory, complete with tables, relations,and views. A DataSet is designed to work without any continuing connection to the original data source. Data in a DataSet is bulk-loaded, rather than being loaded on demand. There's no concept of cursor types in a DataSet. DataSets have no current record pointer You can use For Each loops to move through the data.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    22/27

    You can store many edits in a DataSet, and write them to the original data source in a singleoperation. Though the DataSet is universal, other objects in ADO.NET come in different versions for differentdata sources.

    52. What are the Application_Start and Session_Start subroutines used for?Ans : This is where you can set the specific variables for the Application and Session objects.

    53. Can you explain what inheritance is and an example of when you might use it?Ans : When you want to inherit (use the functionality of) another class. Example: With a base classnamed Employee, a Manager class could be derived from the Employee base class.

    54. Whats MSIL, and why should developers need an appreciation of it if at all?Ans : MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get convertedto MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installedcomputer.

    55. Which method do you invoke on the DataAdapter control to load your generated datasetwith data?Ans : The Fill() method.

    56. Can you edit data in the Repeater control?Ans : No, it just reads the information from its data source.

    57. Which template must you provide, in order to display data in a Repeater control?Ans : ItemTemplate.

    58. How can you provide an alternating color scheme in a Repeater control?Ans : Use the AlternatingItemTemplate.

    59. What property must you set, and what method must you call in your code, in order tobind the data from a data source to the Repeater control?Ans : You must set the DataSource property and call the DataBind method.

    60. Name two properties common in every validation control?

    Ans : ControlToValidate property and Text property.

    61. Which control would you use if you needed to make sure the values in two differentcontrols matched?Ans : CompareValidator control.

    62. How many classes can a single .NET DLL contain?Ans : It can contain many classes.

    63. What is the lifespan for items stored in ViewState?Ans : Item stored in ViewState exist for the life of the current page. This includes postbacks (to thesame page).

    64. What does the "EnableViewState" property do? Why would I want it on or off?

    Ans : It allows the page to save the users input on a form across postbacks. It saves the server-sidevalues for a given control into ViewState, which is stored as a hidden value on the page beforesending the page to the clients browser. When the page is posted back to the server the servercontrol is recreated with the state stored in viewstate.

    65. What are the different types of Session state management options available withASP.NET?Ans : ASP.NET provides In-Process and Out-of-Process state management. In-Process stores thesession in memory on the web server. This requires the a "sticky-server" (or no load-balancing) sothat the user is always reconnected to the same web server. Out-of-Process Session state

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    23/27

    management stores data in an external data source. The external data source may be either a SQLServer or a State Server service. Out-of-Process state management requires that all objects stored insession are serializable.

    66. What is the difference between Value Types and Reference Types?Ans : Value Types uses Stack to store the data where as the later uses the Heap to store the data.

    67. What are user controls and custom controls?Custom controls: A control authored by a user or a third-party software vendor that does notbelong to the .NET Framework class library. This is a generic term that includes user controls. Acustom server control is used in Web Forms (ASP.NET pages). A custom client control is used inWindows Forms applications.

    User Controls: In ASP.NET: A user-authored server control that enables an ASP.NET page to be re-used as a server control. An ASP.NET user control is authored declaratively and persisted as a textfile with an .ascx extension. The ASP.NET page framework compiles a user control on the fly to aclass that derives from the System.Web.UI.UserControl class.

    68. What are the validation controls? A set of server controls included with ASP.NET that test userinput in HTML and Web server controls for programmer-defined requirements. Validation controlsperform input checking in server code. If the user is working with a browser that supports DHTML, the

    validation controls can also perform validation using client script.69. Where do you add an event handler? It's the Attributesproperty, the Add function inside thatproperty. e.g. btnSubmit.Attributes.Add("onMouseOver","someClientCode();")

    70. What data type does the RangeValidator control support?Integer,String and Date.

    C# Interview Questions

    1. Whats the implicit name of the parameter that gets passed into the class setmethod? Value, and its datatype depends on whatever variable were changing.

    2. How do you inherit from a class in C#? Place a colon and then the name of the baseclass. Notice that its double colon in C++.

    3. Does C# support multiple inheritance? No, use interfaces instead.

    4. When you inherit a protected class-level variable, who is it available to? Classes inthe same namespace.

    5. Are private class-level variables inherited? Yes, but they are not accessible, solooking at it you can honestly say that they are not inherited. But they are.

    6. Describe the accessibility modifier protected internal. Its available to derivedclasses and classes within the same Assembly (and naturally from the base class itsdeclared in).

    7. C# provides a default constructor for me. I write a constructor that takes a string

    as a parameter, but want to keep the no parameter one. How many constructorsshould I write? Two. Once you write at least one constructor, C# cancels the freebieconstructor, and now you have to write one yourself, even if theres no implementation init.

    8. Whats the top .NET class that everything is derived from? System.Object.

    9. Hows method overriding different from overloading? When overriding, you changethe method behavior for a derived class. Overloading simply involves having a methodwith the same name within the class.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    24/27

    10.What does the keyword virtual mean in the method definition? The method can beover-ridden.

    11.Can you declare the override method static while the original method is non-static? No, you cant, the signature of the virtual method must remain the same, only thekeyword virtual is changed to keyword override.

    12.Can you override private virtual methods? No, moreover, you cannot access private

    methods in inherited classes, have to be protected in the base class to allow any sort ofaccess.

    13.Can you prevent your class from being inherited and becoming a base class forsome other classes? Yes, thats what keyword sealed in the class definition is for. Thedeveloper trying to derive from your class will get a message: cannot inherit from Sealedclass WhateverBaseClassName. Its the same concept as final class in Java.

    14.Can you allow class to be inherited, but prevent the method from being over-ridden? Yes, just leave the class public and make the method sealed.

    15.Whats an abstract class? A class that cannot be instantiated. A concept in C++ knownas pure virtual method. A class that must be inherited and have the methods over-ridden.Essentially, its a blueprint for a class without any implementation.

    16.When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)? When at least one ofthe methods in the class is abstract. When the class itself is inherited from an abstractclass, but not all base abstract methods have been over-ridden.

    17.Whats an interface class? Its an abstract class with public abstract methods all ofwhich must be implemented in the inherited classes.

    18.Why cant you specify the accessibility modifier for methods inside the interface?They all must be public. Therefore, to prevent you from getting the false impression thatyou have any freedom of choice, you are not allowed to specify any accessibility, its publicby default.

    19.Can you inherit multiple interfaces? Yes, why not.

    20.And if they have conflicting method names? Its up to you to implement the methodinside your own class, so implementation is left entirely up to you. This might cause aproblem on a higher-level scale if similarly named methods from different interfacesexpect different data, but as far as compiler cares youre okay.

    21.Whats the difference between an interface and abstract class? In the interface allmethods must be abstract; in the abstract class some methods can be concrete. In theinterface no accessibility modifiers are allowed, which is ok in abstract classes.

    22.How can you overload a method? Different parameter data types, different number ofparameters, different order of parameters.

    23.If a base class has a bunch of overloaded constructors, and an inherited class hasanother bunch of overloaded constructors, can you enforce a call from aninherited constructor to an arbitrary base constructor? Yes, just place a colon, and

    then keyword base (parameter list to invoke the appropriate constructor) in theoverloaded constructor definition inside the inherited class.

    24.Whats the difference between System.String and System.StringBuilder classes?System.String is immutable; System.StringBuilder was designed with the purpose ofhaving a mutable string where a variety of operations can be performed.

    25.Whats the advantage of using System.Text.StringBuilder over System.String?StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text.Strings are immutable, so each time its being operated on, a new instance is created.

    26.Can you store multiple data types in System.Array? No.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    25/27

    27.Whats the difference between the System.Array.CopyTo() andSystem.Array.Clone()? The first one performs a deep copy of the array, the second oneis shallow.

    28.How can you sort the elements of the array in descending order? By calling Sort()and then Reverse() methods.

    29.Whats the .NET datatype that allows the retrieval of data by a unique key?

    HashTable.

    30.Whats class SortedList underneath? A sorted HashTable.

    31.Will finallyblock get executed if the exception had not occurred? Yes.

    32.Whats the C# equivalent of C++ catch (), which was a catch-all statement forany possible exception? A catch block that catches the exception of typeSystem.Exception. You can also omit the parameter data type in this case and just writecatch {}.

    33.Can multiple catch blocks be executed? No, once the proper catch code fires off, thecontrol is transferred to the finally block (if there are any), and then whatever follows thefinally block.

    34.Why is it a bad idea to throw your own exceptions? Well, if at that point you knowthat an error has occurred, then why not write the proper code to handle that errorinstead of passing a new Exception object to the catch block? Throwing your ownexceptions signifies some design flaws in the project.

    35.Whats a delegate? A delegate object encapsulates a reference to a method. In C++they were referred to as function pointers.

    36.Whats a multicast delegate? Its a delegate that points to and eventually fires offseveral methods.

    37.Hows the DLL Hell problem solved in .NET? Assembly versioning allows theapplication to specify not only the library it needs to run (which was available underWin32), but also the version of the assembly.

    38.What are the ways to deploy an assembly? An MSI installer, a CAB archive, andXCOPY command.

    39.Whats a satellite assembly? When you write a multilingual or multi-cultural applicationin .NET, and want to distribute the core application separately from the localized modules,the localized assemblies that modify the core application are called satellite assemblies.

    40.What namespaces are necessary to create a localized application?System.Globalization, System.Resources.

    41.Whats the difference between // comments, /* */ comments and ///comments? Single-line, multi-line and XML documentation comments.

    42.How do you generate documentation from the C# file commented properly with acommand-line compiler? Compile it with a /doc switch.

    43.Whats the difference between and XML documentation tag? Singleline code example and multiple-line code example.

    44.Is XML case-sensitive? Yes, so and are different elements.

    45.What debugging tools come with the .NET SDK? CorDBG command-line debugger,and DbgCLR graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you

    must compile the original C# file using the /debug switch.

    46.What does the This window show in the debugger? It points to the object thatspointed to by this reference. Objects instance data is shown.

  • 8/9/2019 ASP.net- SQL Interview Questions With Answers

    26/27

    47.What does assert() do? In debug compilation, assert takes in a Boolean condition as aparameter, and shows the error dialog if the condition is false. The program proceedswithout any interruption if the condition is true.

    48.Whats the difference between the Debug class and Trace class? Documentationlooks the same. Use Debug class for debug builds, use Trace class for both debug andrelease builds.

    49.Why are there five tracing levels in System.Diagnostics.TraceSwitcher? Thetracing dumps can be quite verbose and for some applications that are constantly runningyou run the risk of overloading the machine and the hard drive there. Five levels rangefrom None to Verbose, allowing to fine-tune the tracing activities.

    50.Where is the output of TextWriterTraceListener redirected? To the Console or a textfile depending on the parameter passed to the constructor.

    51.How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe processto the DbgClr debugger.

    52.What are three test cases you should go through in unit testing? Positive test cases(correct data, correct output), negative test cases (broken or missing data, properhandling), exception test cases (exceptions are thrown and caught properly).

    53.Can you change the value of a variable while debugging a C# application? Yes, ifyou are debugging via Visual Studio.NET, just go to Immediate window.

    54.Explain the three services model (three-tier application). Presentation (UI),business (logic and underlying code) and data (from storage or other sources).

    55.What are advantages and disadvantages of Microsoft-provided data providerclasses in ADO.NET? SQLServer.NET data provider is high-speed and robust, butrequires SQL Server license purchased from Microsoft. OLE-DB.NET is universal foraccessing other sources, like Oracle, DB2, Microsoft Access and Informix, but its a .NETlayer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecatedlayer provided for backward compatibility to ODBC engines.

    56.Whats the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed.

    57.What is the wildcard character in SQL? Lets say you want to query database withLIKE for all employees whose name starts with La. The wildcard character is %, theproper query with LIKE would involve La%.

    58.Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is oneunit of work and does not dependent on previous and following transactions), Consistent(data is either committed or roll back, no in-between case where something has beenupdated and something hasnt), Isolated (no transaction sees the intermediate results ofthe current transaction), Durable (the values persist if the data had been committed evenif the system crashes right after).

    59.What connections does Microsoft SQL Server support? Windows Authentication (viaActive Directory) and SQL Server authentication (via Microsoft SQL Server username andpasswords).

    60.Which one is trusted and which one is untrusted? Windows Authentication is trustedbecause the username and password are checked with the Active Directory, the SQLServer authentication is untrusted, since SQL Server is the only verifier participating in thetransaction.

    61.Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications.

    62.What does the parameter Initial Catalog define ins