Saturday, 21 April 2012

Script for swapping gender in sql server through CASE (Without Using Cursor)

I want to share you my experience about an interview where i was asked to write script for swapping gender using cursor and without using cursor.
   In my previous post I mentioned "Script for swapping gender through CURSOR" .Here I am sharing swapping gender using CASE .

Step 1: First of all create a table ,here "genderTest"

            CREATE TABLE  genderTest (id nvarchar(20) PRIMARY KEY,empname nvarchar(20),gender           nvarchar(1))

Step 2:Now insert some values in table

       INSERT INTO gendertest VALUES ('1','ashish','m')
       INSERT INTO gendertest VALUES ('2','nandani','f')
       INSERT INTO gendertest VALUES ('3','chandrasen','m')
       INSERT INTO gendertest VALUES ('4','priynka','f')
       INSERT INTO gendertest VALUES ('5','sonam','f')
       INSERT INTO gendertest VALUES ('6','guru','m')
       INSERT INTO gendertest VALUES ('7','faisal','m')
       INSERT INTO gendertest VALUES ('8','priti','f')

Step 3: Execute following query


           UPDATE genderTest 
           SET gender=
          CASE gender
          WHEN 'f' THEN 'm'
          ELSE 'f'
      END
   Above script will swap gender.
    





Thursday, 19 April 2012

Technology Improver: Script for swapping gender in sql server through Cursor

Script for swapping gender in sql server through Cursor


Step 1:Create table ,here GenderConvert

--create table GenderConvert(name nvarchar(20),gender nvarchar(1))

Step 2:Insert some Values in table

--insert into genderconvert values('ashish', 'm' )
--insert into genderconvert values('sonam', 'f' )
--insert into genderconvert values('priya', 'f' )
--insert into genderconvert values('sonu', 'm' )
--insert into genderconvert values('anshu', 'f' )
--insert into genderconvert values('vinod', 'm' )
--insert into genderconvert values('pappu ', 'm' )
--insert into genderconvert values('pavan', 'm' )
--insert into genderconvert values('priynka', 'f' )
--insert into genderconvert values('sonali', 'f' )
--insert into genderconvert values('guru', 'm' )

STEP 3:Execute this script (cursor)

DECLARE @name nvarchar(20)
DECLARE @gender nvarchar(1)
DECLARE @MyCursor CURSOR

--Assign table to cursor variable

SET @MyCursor = CURSOR FOR 
SELECT name,gender FROM genderconvert

--Open cursor

OPEN @MyCursor

--Fetch cursor row on by one

FETCH NEXT 
FROM @MyCursor INTO @name , @gender
WHILE @@FETCH_STATUS = 0
BEGIN

if(@gender = 'm' )
BEGIN 
UPDATE  genderconvert set gender='f' where name=@name
END
else
BEGIN 
UPDATE  genderconvert set gender='m' where name=@name
END
FETCH NEXT FROM @MyCursor into  @name,@gender
END


           After executing this script gender will be swap.Please give your valuable review if this post helpful for you.

Thursday, 19 January 2012

CURSOR IN SQL SERVER 2008


-----------     Cursor    -------------------
            Microsoft SQL Server statements produce a complete result set, but there are times when the results are best processed one row at a time. Opening a cursor on a result set allows processing the result set one row at a time. You can assign a cursor to a variable or parameter with a cursor data type.
            Some time we need to do operation on a particular row of result set or small block of rows at a time. Cursors are an extension to result sets that provide that mechanism.
           
To use cursors in SQL procedures, you need to do the following:
1:Declare a cursor that defines a result set.
2:Open the cursor to establish the result set.
3:Fetch the data into local variables as needed from the cursor, one row at a time.
4:Close the cursor when done
5:Deallocate the cursor




1:DECLARE CURSOR(T-SQL)
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ]
     [ FORWARD_ONLY | SCROLL ]
     [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
     [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]
     [ TYPE_WARNING ]
     FOR select_statement
     [ FOR UPDATE [ OF column_name [ ,...n ] ] ]
[;]

LOCAL:
         Scope of Local cursor is only to batch , stored procedure , or trigger in   which it is declared. And LOCAL cursor automatically deallocated when container block ,sp or trigger terminated.



GLOBAL:
         Specifies that the scope of the cursor is global to the connection. The cursor name can be referenced in any stored procedure or batch executed by the connection. The cursor is     onl   implicitly    deallocated at disconnect.

FORWARD_ONLY

          - Specifies that cursor can only fetch data sequentially from the first to the last row. FETCH NEXT is the only fetch option supported. It is the fastest cursor that you can update.
             The effects of all INSERT, UPDATE, and DELETE statements made by the current user or committed by other users that affect rows in the result set are visible as the rows are fetched from the cursor. Because the cursor cannot be scrolled backward, changes made to rows in the database after the row was fetched are not visible by using the cursor.                                                                
 Note: If cursor is not declared forward-only OR scroll  , then by default it is forward-only.
STATIC: Defines a cursor that makes a temporary copy of the data in tempdb to be used by the cursor. Therefore modification made to base table does not reflect to temporary table , and this cursor does not allow modification.
DYNAMIC: Defines a cursor that reflects all data changes made to the rows in its result set as you scroll around the cursor. The data values, order, and membership of the rows can change on each fetch. The FETCH ABSOLUTE option is not supported with dynamic cursors.
FAST_FORWARD: Specify forward-only , read-only cursor. FAST_FORWARD can not be applied if SCROLL or  FOR_UPDATE is specified.
READ_ONLY:  Prevent updates made through this cursor.
SCROLL_LOCK: specify that updation  or deletion made through this cursor guarantee to succeed. Because SQL server lock the corresponding row.  
OPTIMISTIC: Specifies that positioned updates or deletes made through the cursor do not succeed if the row has been updated since it was read into the cursor. SQL Server does not lock rows as they are read into the cursor.
TYPE_WARNING - Specifies that if the cursor will be implicitly converted from the requested type to another, a warning message will be sent to the client.

FOR UPDATE [OF column_name [,...n]]
            Defines updatable columns within the cursor. If OF column_name [,...n] is supplied, only the columns listed allow modifications. If UPDATE is specified without a column list, all columns can be updated, unless the READ_ONLY concurrency option was specified.


2:OPEN   CURSOR 
Syntax for opening cursor is
Open <cursor_name>
3:FETCH ROW FROM CURSOR
FETCH [NEXT | PRIOR | FIRST | LAST |ABSOLUTE{n}|RELATIVE{n}]                                                                      [FROM]    <cursor_name>   [INTO @variable_name[1,2,…n variable]]
Let us define the terms used in syntax---
NEXT: Returns the immediate  next row .And increment current row pointer to  that row.
PRIOR: Returns the immediate  previous row .And increment current row pointer to  that row. 
FIRST: Returns the first row in the cursor and makes it the current row.
LAST: Returns the last row in the cursor and makes it the current row.
ABSOLUTE{ n}          :Return nth row of result set. If n is positive, counting start from top of result set .If n is negative , counting start from bottom of result set. In both situation returned row is made as new current row. If n is 0 no row is returned.
REALTIVE { n }: Same           functionality as absolute , but only difference is that counting start from current row ,forward of backward ,according to sign of n.                                               
NOTE:
J If either FORWARD_ONLY or FAST_FORWARD is specified, NEXT is the only FETCH option supported.
JIf DYNAMIC, FORWARD_ONLY or FAST_FORWARD are not specified, and one of KEYSET, STATIC, or SCROLL are specified, all FETCH options are supported.
JDYNAMIC SCROLL cursors support all the FETCH options except ABSOLUTE.
4: CLOSE CURSOR
 Closes an open cursor by releasing the current result set and freeing any cursor locks held on the rows on which the cursor is positioned. CLOSE leaves the data structures available for reopening, but fetches and positioned updates are not allowed until the cursor is reopened. CLOSE must be issued on an open cursor; CLOSE is not allowed on cursors that have only been declared or are already closed.

SYNTAX:
       CLOSE   <cursor_name>

5: DEALLOCATE CURSOR
Removes a cursor reference. When the last cursor reference is deallocated, the data structures comprising the cursor are released by Microsoft SQL Server.
SIMPLE EXAMPLE:
DECLARE @a  nvarchar(50)
DECLARE @myCursor  CURSOR
SET  @myCursor=CURSOR FOR SELECT TOP 10  propertyid FROM properties

OPEN @myCursor
FETCH NEXT
FROM  @myCursor into @a
WHILE @@FETCH_STATUS =0
BEGIN
PRINT @a
FETCH NEXT
FROM  @myCursor into @a
END
CLOSE @myCursor
DEALLOCATE @myCursor





WHAT @@FETCH_STATUS DO HERE?
            @@FETCH_STATUS              is called cursor function, which is in build function.
It return the status  of last cursor FETCH statement.
If it is 0; the FETCH statement was successful
If it is -1; failed or row was beyond the result set
If it is -2;the row fetched is missing

Friday, 16 December 2011

Top 50 asp.net interview question


  1. Explain the life cycle of an ASP .NET page.
  2. Explain the .NET architecture.
  3. What are object-oriented concepts?
  4. How do you create multiple inheritance in c# and .NET?
  5. When is web.config called?
  6. How many weg.configs can an application have?
  7. How do you set language in weg.config?
  8. What does connection string consist of?
  9. Where do you store connection string?
  10. What is abstract class?
  11. What is difference between interface inhertance and class inheritance?
  12. What are the collection classes?
  13. What are the types of threading models?
  14. What inheritance does VB.NET support?
  15. What is a runtime host?
  16. Describe the techniques for optimizing your application?
  17. Differences between application and session
  18. What is web application virtual directory?
  19. Differences between Active.exe and Dll
  20. Connection pooling in MTS?
  21. If cookies is disabled in client browser, will session tracking work?
  22. How do you make your site SSL-enabled?
  23. Will the following code execute successfully: response.write(’value of i=’+i);
  24. What are the provides available with VB.NET?
  25. What is a Process, Sesion and Cookie?
  26. What are Abstract base classes?
  27. What are the Difference between bstract base classes and Abstrat classes
  28. What are interface in .NET?
  29. How is Polymorphism supports in .NET?
  30. What are the 2 types of polymorphism supports in .NET?
  31. Types of compatibilities and explain them.
  32. What is aggregative? How can it be implements in .NET?
  33. Difference between COM components and .NET components?how to register it
  34. Difference between early binding and late binding?
  35. ASP.NET OBJECTS?
  36. Asp.NET life cycle? When request mode
  37. Explain ADO and its objects.
  38. What is side by side execution?
  39. Explain serialization?
  40. Explain a class access specifiers and method acess specifiers.
  41. What is the difference between overloading and overriding ? how can this be .NET
  42. Explain virtual function and its usage.
  43. How do you implement inhetance in .NET?
  44. If I want to override a method 1 of class A and this class B then how do you declared
  45. Explain friend and protected friend.
  46. Explain multiple and multi_level inheritance in .NET?
  47. Name all kind of access specifiers for a class and for methods?
  48. On ODP.NET
  49. What is non-derterministic finalization?
  50. What is isPostback property?

C# interview Question for fresher


  1. What’s 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 it’s being operated on, a new instance is created.
  2. Can you store multiple data types in System.Array? No.
  3. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.
  4. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
  5. What’s the .NET datatype that allows the retrieval of data by a unique key?HashTable.
  6. What’s class SortedList underneath? A sorted HashTable.
  7. Will finally block get executed if the exception had not occurred? Yes.
  8. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
  9. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
  10. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
  11. What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
  12. What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods.
  13. How’s the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
  14. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
  15. What’s a satellite assembly? When you write a multilingual or multi-cultural application in .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.
  16. What namespaces are necessary to create a localized application?System.Globalization, System.Resources.
  17. What’s the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments.
  18. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch.
  19. What’s the difference between <c> and <code> XML documentation tag? Single line code example and multiple-line code example.
  20. Is XML case-sensitive? Yes, so <Student> and <student> are different elements.
  21. 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.
  22. What does the This window show in the debugger? It points to the object that’s pointed to by this reference. Object’s instance data is shown.
  23. What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
  24. What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
  25. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.
  26. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.
  27. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.
  28. 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, proper handling), exception test cases (exceptions are thrown and caught properly).
  29. Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
  30. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
  31. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
  32. What’s 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.
  33. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
  34. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit 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 been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).
  35. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
  36. Which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
  37. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications.
  38. What does the parameter Initial Catalog define inside Connection String?The database name to connect to.
  39. What’s the data provider name to connect to Access database? Microsoft.Access.
  40. What does Dispose method do with the connection object? Deletes it from the memory.
  41. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.