353
Are you looking for a simple and efficient way to copy data from one table to another in your database? If so, you’re in luck! In this post, we’ll explore the powerful “SELECT INTO” statement, which allows you to easily create a new table with the exact same structure and data as an existing table. This can be incredibly useful for tasks such as backing up data, creating test environments, or simply duplicating existing data for further analysis. So let’s dive in and discover how you can save time and effort with this simple SQL statement. And don’t forget to try it out for yourself and see just how easy it is!
T-Sql
USE [DatabasenameHere] --Replace "DatabasenameHere" with the name of the database you want to use.
GO
-- Create the original table
CREATE TABLE [dbo].[OriginalTable] (
[ID] INT PRIMARY KEY,
[FirstName] VARCHAR(50),
[LastName] VARCHAR(50),
[Age] INT
);
-- Insert some sample data into the original table
INSERT INTO [dbo].[OriginalTable] ([ID], [FirstName], [LastName], [Age])
VALUES (1, 'Erni', 'Manayon', 55),
(2, 'Ike', 'Hilario', 62),
(3, 'Jerome', 'Ocares', 47),
(4, 'Gd', 'Relly', 35),
(5, 'Ern', 'Rom', 77)
------------------------------------------------------------------------
-- Copies data from one table to a new table using SELECT INTO statement
------------------------------------------------------------------------
SELECT *
INTO [dbo].[NewTable]
FROM [dbo].[OriginalTable]
--WHERE ID IN(5)
/*** To remove the sample objects
DROP TABLE OriginalTable
DROP TABLE NewTable
***/
/* The script above demonstrates how to use the SELECT INTO statement to copy data from one table to a new table with the same structure. */
/* To use this script, simply copy and paste it into a new query window in SQL Server Management Studio,
replace 'OriginalTable' with the name of the table you want to copy data from,
and replace 'NewTable' with the name of the new table you want to copy the data to.
Then execute the script to copy the data. */
/* You can also add a WHERE clause to the SELECT statement to filter the data being copied to. */