My Sql concepts

354
-1

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
354
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
7
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

My Sql concepts

  1. 1. 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 dont have a unique column, you can use an identity column.) Table variables dont participate in transactions, logging or locking. This means theyre faster as they dont require the overhead, but conversely you dont 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 dont 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 youre writing a function you should use table variables over temp tables unless theres 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 ValuesFunctionSCOPE_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.
  2. 2. IDENT_CURRENT:: Returns the last identity value generated for a specific table in any sessionand any scope. Default Schema is “dbo.” Or define it nVarchar takes double the size defined. It supports Unicodecreate database Pragyasp_who2sp_helptext sp_who2use 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 CustomerAlter table customerAdd test nvarchar(200)Alter table Customerdrop column testAlter table Customer --not preferredAdd Primary Key (CustomerID)Create Table CustPhone(PhoneID int Primary Key, CustomerID int Null, Phone Int)Alter table CustPhonedrop constraint FKCustomerID
  3. 3. Alter table CustPhoneAdd Constraint UniqueNameCreate Table Orders(OrderID INT IDENTITY (1,1) Not Null Check (OrderID between 1 and 1000000), OrderDate datetime not null, CustomerID integer Foreign Key referencesCustomer(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.
  4. 4. SELECT [CustomerID] ,[AddressID] ,[AddressType] ,[rowguid] ,[ModifiedDate] FROM [AdventureWorks].[SalesLT].[CustomerAddress] where CustomerID= 29489 and AddressID= 1069GOSELECT [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 OfficeClick Display Estimated Executed Plan button on topRetrieve Identityselect IDENT_CURRENT(Pragya)select SCOPE_IDENTITY()select @@IDENTITYinsert into Customer(Name, CreateDateTime, CreditLimit) values (Hello,GETDATE(), 5000)sp_help Customerselect * from Customer--not preferred-- NON Clustered Primary KeyAlter table OrdersAdd constraint PKCustomer1 Primary Key NONCLUSTERED (OrderID)  Concatenate nameSELECT [Title] ,[FirstName] ,[MiddleName] ,[LastName], + isNull (Title, )+ FirstName +LastName As EmpName FROM [AdventureWorks].[SalesLT].[Customer]
  5. 5. --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 datatypemust 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 *fromSalesLT.Customer ainner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerIDinner join SalesLT.Address b on CA.AddressID = b.AddressIDwhere b.StateProvince= washington
  6. 6. --Order byFirstName desc --Cannot use here--At end of queryUNIONselect *fromSalesLT.Customer ainner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerIDinner join SalesLT.Address b on CA.AddressID = b.AddressIDwhere b.StateProvince= TexasOrder by FirstName asc---------------EXCEPT-----------------------select *fromSalesLT.Customer ainner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerIDinner join SalesLT.Address b on CA.AddressID = b.AddressIDwhere b.StateProvince= washingtonEXCEPT -- same no of column and same datatypeselect *fromSalesLT.Customer ainner join SalesLT.SalesOrderHeader CA on a.CustomerID = CA.CustomerIDinner join SalesLT.Address b on CA.AddressID = b.AddressIDwhere b.StateProvince= TexasOrder by FirstName asc----------Working with Intersect--------HW--------------------========================---------UnionAll----------Create Table t1(i int)insert into t1select 1unionselect 2union select 3--select distinct * from t1select * from t1unionselect * from t1select * from t1union allselect * from t1---select distinct * from t1select * from t1 -- Expensive performanceunionselect * from t1select i from t1group by i================================================-------CUrrent Date Time
  7. 7. 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/2011SELECT 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

×