9
Some points to consider when choosing Temporary, Global Temp Tables, between them: Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option. Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.) Table variables don't participate in transactions, logging or locking. This means they're faster as they don't require the overhead, but conversely you don't get those features. So for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated! Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not. You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront. You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter). Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise. Both table variables and temp tables are stored in tempdb. This means you should be aware of issues such as COLLATION problems if your database collation is different to your server collation; temp tables and table variables will by default inherit the collation of the server, causing

My Sql concepts

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: My Sql concepts

Some points to consider when choosing Temporary, Global Temp Tables, between them:

Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option.

Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.)

Table variables don't participate in transactions, logging or locking. This means they're faster as they don't require the overhead, but conversely you don't get those features. So for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated!

Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not.

You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront.

You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter).

Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise.

Both table variables and temp tables are stored in tempdb. This means you should be aware of issues such as COLLATION problems if your database collation is different to your server collation; temp tables and table variables will by default inherit the collation of the server, causing problems if you want to compare data in them with data in your database.

Global Temp Tables (##tmp) are another type of temp table available to all sessions and users.

Retrieving SQL Server Identity Column Values

Function

SCOPE_IDENTITY:: Returns the last identity value within the current execution scope. SCOPE_IDENTITY is recommended for most scenarios.

@@IDENTITY:: Contains the last identity value generated in any table in the current session. @@IDENTITY can be affected by triggers and may not return the identity value that you expect.

Page 2: My Sql concepts

IDENT_CURRENT:: Returns the last identity value generated for a specific table in any session and any scope.

Default Schema is “dbo.” Or define it nVarchar takes double the size defined. It supports Unicode

create database Pragya

sp_who2sp_helptext 'sp_who2'

use mydbselect * from demo1

--------------------------use Pragyacreate Table test1 (i int) --permanentcreate Table #test1 (i int) --tempcreate Table ##test1 (i int) --global tempDeclare test1(i int)

Create Table test2(i int)

Create Table Customer(CustomerID INT IDENTITY (1000,1) Not Null, Name nvarchar(100),CreateDateTime datetime,CreditLimit decimal(12,5))insert into Customer( Name,CreateDateTime, CreditLimit) values ('test', Getdate(), 1000)

select * from Customer

Alter table customer Add test nvarchar(200)

Alter table Customerdrop column test

Alter table Customer --not preferredAdd Primary Key (CustomerID)

Create Table CustPhone(PhoneID int Primary Key, CustomerID int Null, Phone Int)

Alter table CustPhonedrop constraint FKCustomerID

Page 3: My Sql concepts

Alter table CustPhoneAdd Constraint UniqueName

Create Table Orders(OrderID INT IDENTITY (1,1) Not Null Check (OrderID between 1 and 1000000), OrderDate datetime not null, CustomerID integer Foreign Key references Customer(CustomerID))

insert into Orders(OrderDate) values ( Getdate())

Sp_help Orders

Four -Part Naming:: Server, Database, Schema, Object Name A Cartesian join will get you a Cartesian product.

A Cartesian join is when you join every row of one table to every row of another table. You can also get one by joining every row of a table to every row of itself.

Page 4: My Sql concepts

SELECT [CustomerID] ,[AddressID] ,[AddressType] ,[rowguid] ,[ModifiedDate] FROM [AdventureWorks].[SalesLT].[CustomerAddress] where CustomerID= '29489' and AddressID=' 1069' GO

SELECT [CustomerID] ,[AddressID] ,[AddressType] ,[rowguid] ,[ModifiedDate] FROM [AdventureWorks].[SalesLT].[CustomerAddress] where CustomerID= '29489' or AddressID=' 1069' SELECT [CustomerID] ,[AddressID] ,[AddressType] ,[rowguid] ,[ModifiedDate] FROM [AdventureWorks].[SalesLT].[CustomerAddress] where CustomerID= '29489' or AddressID=' 1069' and AddressType= 'Main Office'

Click Display Estimated Executed Plan button on top

Retrieve Identityselect IDENT_CURRENT('Pragya')select SCOPE_IDENTITY()select @@IDENTITY

insert into Customer(Name, CreateDateTime, CreditLimit) values ('Hello', GETDATE(), 5000)

sp_help Customer

select * from Customer

--not preferred-- NON Clustered Primary KeyAlter table Orders Add constraint PKCustomer1 Primary Key NONCLUSTERED (OrderID)

Concatenate nameSELECT [Title] ,[FirstName] ,[MiddleName] ,[LastName],' '+ isNull (Title, '')+ FirstName +LastName As EmpName

FROM [AdventureWorks].[SalesLT].[Customer]

Page 5: My Sql concepts

--Self JoinSELECT emp.empid, emp.title, m.title, from emp Einner join emp M on e.m_id=m.e_id

---Without joinSELECT emp.empid, emp.title, m.title, from emp E, emp M where e.m_id=m.e_id Select mgrId, COUNT(empId) from employee group by mngrId -- for null mngr Select EmpID, MngID, Title from Employee where mngrId=3 begin Tran set rowcount 100 -- only 100 rows will get effected like top 100 Update employee set loginId=null --Alter query is faster than update Alter table Employee alter column LoginId nvarchar(256) null Select mgrId, COUNT(empId), COUNT(LoginID), SUM(LoginID) --operator datatype must not b varchar from employee E group by mngrId Select mgrId, COUNT(empId), COUNT(isnull(LoginID, 'a')) from employee E group by mngrId ---------------------------------------------------- --------Mngr total emp count is >20------- Select mgrId, COUNT(EmpId) from Employee E group by mngrId having COUNT(empId)>20 -------------Another way---Derived Table----- Select * from (Select mgrId, COUNT(EmpId) emp from Employee E group by mngrId)AA where emp>20

---UNION---select *from SalesLT.Customer ainner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerIDinner join SalesLT.Address b on CA.AddressID = b.AddressIDwhere b.StateProvince= 'washington'

Page 6: My Sql concepts

--Order byFirstName desc --Cannot use here--At end of queryUNIONselect *from SalesLT.Customer ainner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerIDinner join SalesLT.Address b on CA.AddressID = b.AddressIDwhere b.StateProvince= 'Texas'Order by FirstName asc

---------------EXCEPT-----------------------

select *from SalesLT.Customer ainner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerIDinner join SalesLT.Address b on CA.AddressID = b.AddressIDwhere b.StateProvince= 'washington'EXCEPT -- same no of column and same datatypeselect *from SalesLT.Customer ainner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerIDinner join SalesLT.Address b on CA.AddressID = b.AddressIDwhere b.StateProvince= 'Texas'Order by FirstName asc

----------Working with Intersect--------HW--------------------========================---------UnionAll----------Create Table t1(i int)insert into t1select 1union select 2union select 3

--select distinct * from t1select * from t1unionselect * from t1

select * from t1union allselect * from t1---select distinct * from t1select * from t1 -- Expensive performanceunion select * from t1

select i from t1group by i================================================

-------CUrrent Date Time

Page 7: My Sql concepts

select GETDATE()select LEFT('Pragya', 2) -- first 2select Right('Pragya', 2)select MONTH(getdate())select DATEPART(M,getdate())create table td(dt varchar(10))Insert into td values('01/01/2011')select * from tdselect dt, CAST(dt as DATE),CAST(dt as datetime) from td

-- first day of month and last day of mnth with date-- HWDECLARE @Today DATETIMESELECT @Today = '8/25/2011'SELECT DATEADD(dd,-(DAY(DATEADD(mm,1,@Today))-1),DATEADD(mm,0,@Today))-----------------------------------------------------SELECT DATEADD(dd, -DAY(DATEADD(m,1,@Today)), DATEADD(m,-2,@Today))Value = 2007-03-31 00:00:00.000