Handy Code for SQL Server | YourSite

Handy Code for SQL Server

SQL SERVER • 749 views

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

🚀 More Blogs You Might Like

Explore more articles and keep learning

Heat Stroke in Summer: Causes, Symptoms, Prevention and What To Do
health
Heat Stroke in Summer: Causes, Symptoms, Prevention and What To Do

Heat Stroke in Summer: Causes, Symptoms, Prevention and What To Do...

👁 10 2026-04-26
Read More →
Alcoholic Fatty Liver Disease: Causes, Symptoms, Risks and How to Improve It
health
Alcoholic Fatty Liver Disease: Causes, Symptoms, Risks and How to Improve It

Alcoholic Fatty Liver Disease: Causes, Symptoms, Risks and How to Improve It...

👁 9 2026-04-26
Read More →
Non-Alcoholic Fatty Liver: Meaning, Causes, Symptoms, and How to Improve It
health
Non-Alcoholic Fatty Liver: Meaning, Causes, Symptoms, and How to Improve It

Non-Alcoholic Fatty Liver: Meaning, Causes, Symptoms, and How to Improve It...

👁 10 2026-04-26
Read More →
The Ultimate Blueprint to Score 70/70 in ISC Class 12 Computer Science
class-1-12-resources
The Ultimate Blueprint to Score 70/70 in ISC Class 12 Computer Science

The Ultimate Blueprint to Score 70/70 in ISC Class 12 Computer Science...

👁 47 2026-04-11
Read More →