Showing posts with label How to's. Show all posts
Showing posts with label How to's. Show all posts

Wednesday, September 18, 2013

How to series TSQL 2


6. How to find second highest

SELECT COL 
FROM TABLE 
ORDER BY COL DESC
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY;


7. How to use multiple cte

;with cte1
as
(select col1, null as col2 from Tab),

cte2
as 
(
select col2, null as col1 from Tab
)

select * from cte1
union
select * from cte2

8 How to rename column
EXEC sp_rename 'TABLENAME.OLD_COLUMNNAME', 'NEW_COLUMNAME', 'COLUMN';
.

How to series TSQL 1


1. How to change col datatype

-- TransDate was in datetime change to date

alter table Transactions 
alter column TransDate date


2.  How to create primary key on a col

alter table TransactionsArchive 
add constraint  PK_TransactionsArchive_KeyID primary key clustered (key_ID);
GO

3.  How to re-sequence an identity column


alter table List_NotesType
drop constraint PK_List_CommentsType

alter table List_NotesType
drop column NoteType

alter table List_NotesType
add NoteType tinyint identity(1,1)

alter table List_NotesType
add constraint PK_List_NoteTypeID primary key clustered (NoteType);

4. How to change a not null col to null

alter table [Notes] 
alter column Comments varchar(500) NULL

5. How to update existing NULL cols with a value

update Notes 
set Comments = t.Description
from Notes n join List_NotesType t on n.Type = t.NoteType
where Noteid in (select Noteid from Notes where Comments is null)