I have a table on SQL Server database from which I need to create different tables for each unique value of a particular column.
I tried below code:
DECLARE @i int
DECLARE @numrows int
DECLARE @indexcount int
DECLARE @Group varchar
DECLARE @temp_table TABLE (
idx smallint Primary Key IDENTITY(1,1), Group varchar(200)
)
-- populate group table
INSERT @temp_table
SELECT distinct Column_3 FROM Existing_Table
-- enumerate the table
SET @i = 1
SET @numrows = (SELECT COUNT(*) FROM @temp_table)
SET @indexcount = (SELECT MAX(idx) FROM @temp_table)
IF @numrows > 0
WHILE (@i <= @indexcount)
BEGIN
-- get the next Group primary key
SET @Group = (SELECT Group FROM @temp_table WHERE idx = @i);
IF OBJECT_ID('dbo.New_Table_@Group', 'U') IS NOT NULL
DROP TABLE dbo.New_Table_@Group;
select Column_1, Column_2
into New_Table_@Group
from Existing_Table where Column_3 = @Group;
-- increment counter for next employee
SET @i = @i + 1
END
This is executing and without prompting any error, but is also failing to give the expected result. It does not create any new table. While executing it shows that so-and-so number of rows affected but when I check the list of tables, no such new table will be created.
Can someone please help achieve the expected result? Any help is much appreciated.
depiction of existing table and new tables to be created - Here is a depiction of the table that I have and the intended resultant table to be achieved.