Handy Code for SQL Server

Rumman Ansari   2020-03-05   Student   SQL SERVER > Important-SQL-Code   536 Share

Example: How to copy One table to another Table ( Both Data with its Structure)

Code:



SELECT * INTO DestinationTable FROM SourceTable


Example: How to create a data like a table

Code:



SELECT * FROM(
SELECT 1 as ID, 'Rambo' as Name
 UNION
SELECT 2 as ID, 'Azmi' as Name
) AS TableName

Example: How to create a data like above and insert into in a table

Code:



SELECT * INTO DestinationTable FROM (
SELECT 1 as ID, 'Sanjay' as Name
 UNION
SELECT 2 as ID, 'Rumman' as Name
) SourceTable


Example:

Code:



 declare @var varchar(50) = '1,3'  
 declare @query varchar(500) = '
 select * from
(
SELECT  Dept, SUM(Salary) as salarySum, ROW_NUMBER() OVER(ORDER BY Dept) AS Row_Number  FROM EmpSalary GROUP BY  Dept
)ta where ta.Row_Number in ('+ @var +')'
select @query as qry


Example:

Code:



 declare @var varchar(50) = '1,3'  
 declare @query varchar(500) = '
 select * from
(
SELECT  Dept, SUM(Salary) as salarySum, ROW_NUMBER() OVER(ORDER BY Dept) AS Row_Number  FROM EmpSalary GROUP BY  Dept
)ta where ta.Row_Number in ('+ @var +')'
exec(@query)


Example: Core Code


-- All the databases that are present
select * from sys.databases

select * from sys.database_files
select physical_name from sys.database_files