What are the difference between DDL, DML and DCL commands?

What are the difference between DDL, DML and DCL commands?

DDL – Data Definition Language: statements used to define the database structure or schema. Some examples:

  • CREATE – to create objects in the database
  • ALTER – alters the structure of the database
  • DROP – delete objects from the database
  • TRUNCATE – remove all records from a table, including all spaces allocated for the records are removed
  • COMMENT – add comments to the data dictionary
  • RENAME – rename an object

They are called Data Definition since they are used for defining the data. That is the structure of the data is known through these DDL commands.

DML – Data Manipulation Language: statements used for managing data within schema objects. Some examples:

  • SELECT – retrieve data from the a database
  • INSERT – insert data into a table
  • UPDATE – updates existing data within a table
  • DELETE – deletes all records from a table, the space for the records remain
  • MERGE – UPSERT operation (insert or update)
  • CALL – call a PL/SQL or Java subprogram
  • EXPLAIN PLAN – explain access path to data
  • LOCK TABLE – control concurrency

DML commands are used for data manipulation. Some of the DML commands
insert,select,update,delete etc. Even though select is not exactly a DML language command oracle still recommends you to consider SELECT as an DML command.

DML are not auto-commit. i.e. you can roll-back the operations, but DDL are auto-commit

DCL – Data Control Language. Some examples:

  • GRANT – gives user’s access privileges to database
  • REVOKE – withdraw access privileges given with the GRANT command

Data Control Language is used for the control of data. That is a user can access any data based on the priveleges given to him. This is done through DATA CONTROL

It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it.

TCL – Transaction Control: statements used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.

  • COMMIT – save work done
  • SAVEPOINT – identify a point in a transaction to which you can later roll back
  • ROLLBACK – restore database to original since the last COMMIT
  • SET TRANSACTION – Change transaction options like isolation level and what rollback segment to use

For revoking the transactions and to make the data commit to the database we use TCL.

Once we commit we cannot rollback. Once we rollback we cannot commit.

Commit and Rollback are generally used to commit or revoke the transactions that are with regard to DML commands.

Source: From different sql experts from internet

javascript value in server side variable

You can get variable from javascript and use it in code behind code in dotnet variable it means server side variable.

Dim strMessage2 As String = “”

Response.Write(“var str1 =
prompt(‘Please Enter Password:’,”);”)

strMessage2 = “document.write(str1);”

Response.Write(strMessage2)

Good question banks for technical interview

http://stackoverflow.com/questions/tagged/index

Some really usefull Short keys in SQL

Some really usefull Short keys in SQL
Next Page F6
previous Pane Shift F6
Hide/Show Result Pane CTRL R

Charindex, small functionality but usefull

CHARINDEX (Transact-SQL)

Searches expression2 for expression1 and returns its starting position if found. The search starts at start_location.

Few good scripts with charindex

select CHARINDEX(‘a’, ‘india’)

–result will be 5

select CHARINDEX( ‘,1,’ ,’,1,2,3,’)
– result would be 3
DECLARE @selectedID VARCHAR(10)
SET @selectedID = ‘1,2′
–SET @selectedID = ‘1,5′

Some times we have to pass comma seprated value to sp and have to cross check with table data, its good script here.

it would give you all records which are passed in parameter @selectedID.

DECLARE @t AS TABLE (tID INT)
INSERT INTO @t VALUES (1)
INSERT INTO @t VALUES (2)
INSERT INTO @t VALUES (3)

SELECT * FROM @t
WHERE  CHARINDEX(‘,’ + CONVERT(VARCHAR(5),tID) + ‘,’, ‘,’ + @selectedID + ‘,’) > 0

basics of SQL Server Transaction Isolation Levels

I read one good article about sql server – transaction isolation level..

You might like it

Articl Summary: This post discusses the basics of SQL Server Transaction Isolation Levels.

http://www.sqlserverandxml.com/2008/08/introduction-to-sql-server-transaction.html

Basics of query process

i have read one good blog which explains basics of query process. Here is the order in which query operators are evaluated. There are 11 levels.

1. FROM
2. ON
3. JOIN
4. WHERE
5. GROUP BY
6. WITH{CUBE | ROLLUP}
7. HAVING
8. SELECT
9. DISTINCT
10. HAVING
11. TOP

First the query processor reads all the rows from the FROM the left table and apply the ON condition with the right table provided in JOIN.

If there are more JOINs the same is done for all the JOINs.

Then the WHERE clause is applied to filter rows.

Then GROUP BY is done

There WITH clause get evaluated followed by HAVING.

Then the columns are selected. (This is the reason why you cannot use a column alias in WHERE or GROUP BY)

Then DISTINCT clause applied

Then ORDER BY is processed…(This is the reason why you CAN use a column alias in the ORDER BY clause)

Then TOP clause get evaluated.

SOURCE : http://knowledgebaseworld.blogspot.com/2008/07/query-operators-evaluation.html

Calling postback event from Javascript

SOURCE : http://www.dotnetspider.com/resources/1521-How-call-Postback-from-Javascript.aspx

Introduction

Postback is a concept introduced in ASP.NET and is a very handy method. Postback is built into the ASP.NET and most of the web controls support it without writing any code.

Calling postback event from Javascript

There may be some scenario where you may want to explicitly postback to the server using some clientside javascript. It is pretty simple to do this.

ASP.NET already creates a client side javascript method as shown below to support Postbacks for the web controls:

function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}

So, all you have to do is, just call this method with appropriate arguments. You may call this as shown below:

<script language=’Javascript’>
__doPostBack(‘__Page’, ‘MyCustomArgument’);
</script>

However, it is not reccommdended to use this method name directly in the client side. The best approach is, generate this piece of code from the code behind file using ASP.NET. This way, you are safe even if Microsft later change the name of the method ‘__doPostBack’ to something else in a future release.

In your code behind file, declare a protected variable as shown below:

Protected PostBackStr As String

Now, in the page load event, write the following code:

PostBackStr = Page.ClientScript.GetPostBackEventReference(Me, “MyCustomArgument”)

The method GetPostBackEventReference() will generate the same piece of client side code that you need to use to call the Postback method. Instead of harcoding the method name __doPostBack, we are asking ASP.NET to tell us what is the method name.

Now insert the following code in your Aspx page:

<script language=’Javascript’>
<%= PostBackStr %>
</script>

At runtime, it will be evaluated as:

<script language=’Javascript’>
__doPostBack(‘__Page’, ‘MyCustomArgument’);
</script>

Remember to insert the above script into some Javascript method/event where you want to call the postback, instead of simply inserting into the page as shown above.

Generaly, when we do any search in application , we make edit from there of specific record in new popup. We do save in popup and close that popup and refresh our parent search page, then if we wanted to make search by default, we can use this method by refreshing page with search button control.

How to identify and handle the postback in code behind ?

You found how to call the postback from javascript. Now you need a way to identify your postback in the code behind file. The second argument the doPostback method becomes helpful here.

Go to the code behind file and write the following code in the Page Load event:

If Page.IsPostBack Then
Dim eventArg As String = Request(“__EVENTARGUMENT”)
If eventArg = “MyCustomArgument” Then
Response.Write(“You got it !”)
End If
End If

Did you notice how we identify if the page is loaded as part of our postback? We used the second argument in the __doPostBack method to pass a value and used that in PageLoad to identify if it is called as a result of our PostBack.

Correlated Joins Using ‘Apply’

SOURCE: http://www.sqlservercentral.com/articles/T-SQL/63115/

One of my cohorts came to me a while back with a SQL Query challenge. He was creating a report for our Live Voice call center application in which he needed to list all Live Voice Transactions within a given date range (easy stuff so far).

The business rules, however, dictate that a Live Voice transaction can result in 1 to many Live Voice calls actually being made. The call center rep will continue making phone calls until they have either reached the customer in question or until it is determined that the call cannot be completed (bad phone number, etc).

This report was required to only show the 3 most recent calls made for each transaction and for each of the calls, it was required to display the call’s disposition (busy, voice mail, no answer, etc). Hmmm…..that’s a little tougher.

Take the following:

--INNER JOIN
SELECT
 lvt.ID,
 lvt.PhoneNumber,
 lvt.CreateDate,
 lvc.CallWindowStart,
 lvc.CallWindowEnd,
 lvc.LVCallDispositionID
FROM
 LVTransaction lvt
INNER JOIN
 LVCall lvc on lvc.LVTransactionID = lvt.ID
Order By
 Lvt.CreateDate,lvc.CreateDate DESC

This example gives me All LVCall records for each LVTransaction. Some LVTransactions have up to a dozen calls made before a customer is reached or before it’s determined that the call cannot be successfully completed. So, this query is close, but not yet what we need.

Any attempts to limit the joined records with correlated logic results in errors due to the fact that the outer query columns are not available to the inner query (out of scope).

Correlated Join?:

--Correlated INNER JOIN Attempt
SELECT
 lvt.ID,
 lvt.PhoneNumber,
 lvt.CreateDate,
 lvc.CallWindowStart,
 lvc.CallWindowEnd,
 lvc.LVCallDispositionID
FROM
 LVTransaction lvt
INNER JOIN
 (SELECT TOP 3 * FROM LVCall WHERE LVTransactionID = lvt.ID ORDER BY CreateDate DESC) lvc on lvc.LVTransactionID = lvt.ID

This frugal attempt yields the following…



Msg 4104, Level 16, State 1, Line 2
The multi-part identifier "lvt.ID" could not be bound.

The plot thickens…

So I muddled around with a few ideas, attempting various flavors of correlated subqueries, using temp tables, using User Defined functions, etc. and I was not able to come up with a solution that I felt adequately met the requirements.

This seemingly simple problem was turning into a fairly painful ordeal…..welcome to my world.

After searching the web for a bit, I finally came up with a workable solution. The APPLY SQL extension introduced with the release of SQL Server 2005. The APPLY statement can be used in your SQL FROM Clause and allows you to call a table returning function for each row of the outer query. Furthermore (and more importantly for our example), it allows you to pass in outer query columns as arguments to the called function.

The apply statement comes in 2 flavors: CROSS APPLY and OUTER APPLY. CROSS APPLY will return All records in the outer query that have a matching record returned by the inner function\query (Similar to an Inner Join). OUTER APPLY will return all records in the outer query whether they have a matching record in the inner function\query or not (Similar to an Outer Join).

In researching the APPLY statement for this article, I came across the following article by Bill Graziano. using CROSS APPLY in SQL Server 2005. This excellent article discusses a very similar scenario to mine and presents the following solution (Using CROSS APPLY):

CROSS APPLY On A UDF:

SELECT C.CustomerID,
 O.SalesOrderID,
 O.TotalDue
FROM
 AdventureWorks.Sales.Customer AS C
CROSS APPLY
 AdventureWorks.dbo.fn_GetTopOrders(C.CustomerID, 3) AS O
ORDER BY
 CustomerID ASC, TotalDue DESC

Notice that Bill is passing in a “3″ to the function to indicate that he wants the 3 TOP orders for each customer (Nearly identical to what we need).

The function used above is defined as follows:

CREATE FUNCTION dbo.fn_GetTopOrders(@custid AS int, @n AS INT)
 RETURNS TABLE
AS
RETURN
 SELECT TOP(@n) *
 FROM Sales.SalesOrderHeader
 WHERE CustomerID = @custid
 ORDER BY TotalDue DESC
GO

So, although this example gives a great example of using CROSS APPLY, it relies on the use of a UDF, which will work great, but I’d like to avoid it if possible. When devising my solution, I realized that a subquery behaves very much like a function in that it essentially returns a set of records to the caller (outer query) so I thought to myself that we should be able to use the OUTER APPLY statement on a subquery……like this:

OUTER APPLY against a SubQuery:

--OUTER APPLY
SELECT
 lvt.ID,
 lvt.PhoneNumber,
 lvt.CreateDate,
 lvc.CallWindowStart,
 lvc.CallWindowEnd,
 lvc.LVCallDispositionID
FROM
 LVTransaction lvt
OUTER APPLY
(
 SELECT top 3 *
 FROM LVCall
 WHERE lvtransactionID = lvt.ID
 Order By CreateDate DESC
 ) as lvc

VOILA !!!!

Notice, my solution does the same thing that Bill’s solution does but it doesn’t require a UDF so it’s a little easier to implement and to read, etc.

This is the pattern we’ve now been using at my work to implement these types of queries. It’s been easy to teach to other engineers on the team, it works well and it doesn’t require creating separate UDF’s for implementation.

In reading Bill’s article, I also noticed a footnote showing another solution that someone else had sent to him that uses ROW_NUMBER() and PARTITIONING. This was actually very interesting to me. I have to admit that I’d never even heard of these features until coming across the article (I guess we learn something every day).

Here’s the solution to my problem using this technique:

ROW_Number() and Partitioning:
--ROW_NUMBER
SELECT
 ID AS LVTransactionID,
 PhoneNumber,
 CreateDate,
 CallWindowStart,
 CallWindowEnd,
 LVCallDispositionID
FROM
(
 SELECT
 lvt.ID,
 lvt.PhoneNumber,
 lvt.CreateDate,
 lvc.CallWindowStart,
 lvc.CallWindowEnd,
 lvc.LVCallDispositionID
 FROM
 LVTransaction lvt
 INNER JOIN
 (
 SELECT *, ROW_Num = ROW_NUMBER() OVER
(PARTITION BY LVCall.LVTransactionID
 ORDER BY LVCall.CreateDate Desc)
 FROM LVCall
 ) lvc on lvc.LVTransactionID = lvt.ID AND lvc.ROW_NUM <= 3
) as result

This interesting solution provides the exact same resultset as Bill’s original example and as my eventual solution. It seems a little more complicated to me, but I have to admit, the subtree cost displayed in the Estimated Query Plan suggests that it would perform better than my solution. I plan on investigating this approach further when I have time.

I’m certain that there are other solutions to this problem. My intent however, with this article is to introduce some T-SQL extensions newly introduced in SQL Server 2005 that you may not have yet come across and to provide a real world example on how their use can solve a real business problem. As other solutions to this same problem come up, I would love to see them. I am concerned with performance as well as ease of application due to the fact that the techniques used must be dispersed throughout our organization so that we are consistent in our implementation with these sorts of problems.

SOURCE: http://www.sqlservercentral.com/articles/T-SQL/63115/

Data Type Mapping




Mapping data types into different environments like .Net and SQL server.

ASP.NET Control DNN KickStart Field type .NET
Framework
SQL
Server
ADO
DataType
Enum
ADO
DataType
Enum
Value
Size Access Oracle Visual
Basic
6.0
Int64
SqlDbType.BigInt
OleDbType.BigInt
bigint adBigInt 20 8 Variant
Byte[]
SqlDbType.VarBinary
OleDbType.Binary
binary
timestamp
adBinary 128 50
8
Raw Variant
Yes/No Boolean
SqlDbType.Bit
OleDbType.Boolean
bit adBoolean 11 1
2
YesNo Boolean
String
OleDbType.BSTR
adBSTR 8
(DataReader) adChapter 136
Text
Document
String
SqlDbType.Char
OleDbType.Char
char adChar 129 X Char String
Money Decimal
SqlDbType.Money
OleDbType.Currency
money
smallmoney
adCurrency 6 8
4
0
Currency Currency
DateTime
OleDbType.DBDate
adDate 7 0 DateTime Date
DateTime
OleDbType.DBDate
adDBDate 133
DBFileTime adDBFileTime 137
DateTime
OleDbType.DBTime
adDBTime 134
Date
Time
DateTime
SqlDbType.DateTime
OleDbType.DBTimeStamp
datetime
smalldatetime
adDBTimeStamp 135 8
4
0
DateTime Date Date
Decimal
OleDbType.Decimal
adDecimal 14 Decimal Variant 6
Double
SqlDbType.Float
OleDbType.Double
float adDouble 5 8
0
Double Float Double
Empty adEmpty 0
External-Exception
OleDbType.Error
adError 10
DateTime
OleDbType.Filetime
adFileTime 64
Guid
SqlDbType.UniqueIdentifier
OleDbType.Guid
uniqueidentifier adGUID 72 16 ReplicationID Variant
Object
OleDbType.IDispatch
adIDispatch 9
Identifier
Number
Int32
SqlDbType.Int
OleDbType.Integer
identity
int
adInteger 3 4
4
AutoNumber
Long Integer
Int Long
Object
OleDbType.IUnknown
adIUnknown 13
Byte[]
SqlDbType.VarBinary
OleDbType.LongVarBinary
image adLongVarBinary 205 2147483647 OLEObject Long Raw
Blob
Variant
String
SqlDbType.VarChar
OleDbType.LongVarChar
text adLongVarChar 201 2147483647 Memo
Hyperlink
Long
Clob
String
String
SqlDbType.NText
OleDbType.VarWChar
ntext adLongVarWChar 203 1073741823 Memo
Hyperlink
NClob String
Decimal
SqlDbType.Decimal
OleDbType.Decimal
decimal
numeric
adNumeric 131 9 Decimal Decimal
Integer
Number
SmallInt
Variant
Object
OleDbType.PropVariant
adPropVariant 138
Single
SqlDbType.Real
OleDbType.Single
real adSingle 4 4 Single Single
Int16,
SqlDbType.SmallInt
OleDbType.SmallInt
smallInt adSmallInt 2 2 Integer Integer
Byte
OleDbType.TinyInt
adTinyInt 16
UInt64
OleDbType.UnsignedBigInt
adUnsignedBigInt 21
UInt32
OleDbType.UnsignedInt
adUnsignedInt 19
UInt16
OleDbType.UnsignedSmallInt
adUnsignedSmallInt 18
Byte
SqlDbType.TinyInt
OleDbType.UnsignedTinyInt
tinyInt adUnsignedTinyInt 17 1 Byte Byte
adUserDefined 132
Byte[]
SqlDbType.VarBinary
OleDbType.VarBinary
varbinary adVarBinary 204 50 ReplicationID Variant
String
SqlDbType.VarChar
OleDbType.VarChar
varchar adVarChar 200 X Text VarChar String
Object
SqlDbType.Variant
OleDbType.Variant
sql_variant adVariant 12 8016 VarChar2 Variant
OleDbType.VarNumeric adVarNumeric 139
String
SqlDbType.NVarChar
OleDbType.VarWChar
nvarchar adVarWChar 202 X Text NVarChar2 String
String
SqlDbType.NChar
OleDbType.WChar
nchar adWChar 130 X String

and the Managed Extensions for C++. The table also includes entries for the Object and String classes, for which many languages have corresponding keywords.

Category Class name Description Visual Basic data type C# data type Managed Extensions for C++ data type JScript data type
Integer Byte An 8-bit unsigned integer. Byte byte char Byte
SByte An 8-bit signed integer.Not CLS-compliant. SByteNo built-in type. sbyte signed char SByte
Int16 A 16-bit signed integer. Short short short short
Int32 A 32-bit signed integer. Integer int int-or-

long

int
Int64 A 64-bit signed integer. Long long __int64 long
UInt16 A 16-bit unsigned integer.Not CLS-compliant. UInt16No built-in type. ushort unsigned short UInt16
UInt32 A 32-bit unsigned integer.Not CLS-compliant. UInt32No built-in type. uint unsigned int-or-

unsigned long

UInt32
UInt64 A 64-bit unsigned integer.Not CLS-compliant. UInt64No built-in type. ulong unsigned __int64 UInt64
Floating point Single A single-precision (32-bit) floating-point number. Single float float float
Double A double-precision (64-bit) floating-point number. Double double double double
Logical Boolean A Boolean value (true or false). Boolean bool bool bool
Other Char A Unicode (16-bit) character. Char char wchar_t char
Decimal A 96-bit decimal value. Decimal decimal Decimal Decimal
IntPtr A signed integer whose size depends on the underlying platform (a 32-bit value on a 32-bit platform and a 64-bit value on a 64-bit platform). IntPtrNo built-in type. IntPtrNo built-in type. IntPtrNo built-in type. IntPtr
UIntPtr An unsigned integer whose size depends on the underlying platform (a 32- bit value on a 32-bit platform and a 64-bit value on a 64-bit platform).Not CLS-compliant. UIntPtrNo built-in type. UIntPtrNo built-in type. UIntPtrNo built-in type. UIntPtr
Class objects Object The root of the object hierarchy. Object object Object* Object
String An immutable, fixed-length string of Unicode characters. String string String* String