how to reset the existing data order number ? i tried alter table tb_shk_user alter column autonum restart with 1, it works only for new data insert the number will start from 1 the number but will duplicated with existing 1.
autonum column attribute
AUTONUM INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1) primary key
or this :
--Save data of your table into temporary table
create table tmptable as
(
select * from tb_shk_user
)
with data;
--Remove all rows into your table
delete from tb_shk_user ;
--Insert into your table all rows with renumber for autonum, be carefull all columns mus be in select except autonum
insert into tb_shk_user overriding system value
select rownumber() over(order by autonum) as newautonum, username, mobilno
from tmptable;
-- Reposition of autoincrement on max + 1
-- Example if 47896 is the max + 1 of autonum after preceding insert
alter table tb_shk_user alter column autonum restart with 47896;
I suppose you want restart for have a good series of id, then you cando it
--Temprary table with key autonum and new num ordered
create table tmptable as (
select autonum, rownumber() over(order by autonum) as newautonum
from tb_shk_user
) with data;
--Update your table with new num
update tb_shk_user f1 overriding system value
set f1.autonum=
(
select f2.newautonum from tmptable f2
where f1.autonum=f2.autonum
)
where exists
(
select * from tmptable f2
where f1.autonum=f2.autonum
);
-- Reposition of autoincrement on max + 1
-- Example if 47896 is the max + 1 of autonum after preceding update
alter table tb_shk_user alter column autonum restart with 47896;
Related
I have a question: I would like to duplicate all the data in the table PlanData where userID='38' and change then the userID of the duplicated data into userID='39'. So UserID is one of many many cols in the table.
How would I be able to do that?
Thanks
Try below -
insert into PlanData(userid, col2,col3)
select 39 as userid,col2,col3 from PlanData where userID='38'
If you don't want to hardcode the column names then you could use a temporary table as a first step.
The example snippet below also uses a temp table for PlanData, for testing reasons.
-- Test table
IF OBJECT_ID('tempdb..#PlanData') IS NOT NULL DROP TABLE #PlanData;
CREATE TABLE #PlanData (ID INT PRIMARY KEY IDENTITY(1,1), userID INT, Col1 VARCHAR(30));
-- Sample Data
insert into #PlanData (userID, Col1) values
(36,'A'),(36,'B'),(36,'C'),
(38,'X'),(38,'Y'),(38,'Z');
-- Create a temporary table with data from the original user
IF OBJECT_ID('tempdb..#tmpPlanData') IS NOT NULL DROP TABLE #tmpPlanData;
SELECT * INTO #tmpPlanData FROM #PlanData WHERE 0=1
UNION ALL
SELECT * FROM #PlanData WHERE userID = 38;
-- Remove the identity column from the temp table
-- This assumes that the ID column is the first column in the table
ALTER TABLE #tmpPlanData DROP COLUMN ID;
-- Set the userId to the new userId in the temporary table
UPDATE #tmpPlanData SET userID = 39;
-- Insert all from the temporary table into the destination table
INSERT INTO #PlanData
SELECT * FROM #tmpPlanData;
-- Check the inserts
SELECT * FROM #PlanData
WHERE userID = 39;
I spent all day creating then manually inserting into some tables I created today that look like this:
ID - Int (Primary Key set to Auto Increment)
Value - Varchar
But then I realized I had forgotten to insert a value of "--" into the first row of each table.
Is it possible to maybe add 1 to the ID no for each of the values currently in the table then insert the "--" value into the first row?
One of the ways to fix it is to update the record with the ID=1 to '--':
update yourTable set Value = '--' where id = 1
Then you will be required to re-insert the first record into the table:
INSERT INTO yourTable (Value)
VALUES('the value that was originally inserted as 1')
However, if the order of the already inserted records is important then you can insert the '--' value as the ID = 0. In this case you need to disable the IDENTITY column using the SET IDENTITY_INSERT:
SET IDENTITY_INSERT yourTable ON
INSERT INTO yourTable (ID, Value)
VALUES(0, '--')
SET IDENTITY_INSERT yourTable OFF
This way the order of inserted records will be preserved and the '--' will be inserted with the ID of 0
BTW, for mySQL you can insert into the IDENTITY column by default
Because Your ID column auto increment (IDENTITY), when you insert, you mustn't insert ID column. To insert your table, you just insert other columns.
Code insert like this:
INSERT INTO Your_Table (ColA, ColB, ...) -- `except identity colums`
VALUES (A, B, ...)
INSERT INTO Your_Table
VALUES (A, B, ...) -- except identity colums
INSERT INTO Your_Table
SELECT ColA, ColB, ... FROM Other_Table -- except identity colums
If Your_Table empty:
INSERT INTO Your_Table (Value)
VALUES ('--')
INSERT INTO Your_Table
SELECT '--'
If not:
UPDATE Your_Table
SET Value = '--'
WHERE ID = 1
------------------------ More Infor -------------------------------------------
If you want to first row have ID = 1. You can set ID column have IDENTITY(1,1). Like this:
CREATE TABLE Your_Table
(
ID INT IDENTITY(1, 1) PRIMARY KEY,
Value VARCHAR(50) NULL
)
Or, After you create Your_Table, you can set right-click Your_Table, select Design, select ID column. Look Column Properties below, expand Identity Specification, Double click (Is identity), then set value Identity Increment and Identity Seed
I have an existing table with existing data and I want to add new column (named ID) with auto-increment and I want to add a unique value for each row.
Is there an other way than fetching all data and do an update for each row to set this value ?
If you need it in a SELECT:
SELECT *, ROW_NUMBER() OVER(ORDER BY ...A ORDER VALUE) as id
FROM yourTable
If you need it in your table:
ALTER TABLE yourTable ADD id int identity(1,1)
Here is a demo for the output of the ALTER TABLE:
CREATE TABLE #temp(name nvarchar(50))
INSERT INTO #temp(name) VALUES(N'Kai'),(N'Bernd'),(N'Flo'),(N'Pete')
SELECT * FROM #temp
-- This is what you need to do
ALTER TABLE #temp
ADD id int identity(1,1) -- This will add and fill the new column
SELECT * FROM #temp
DROP TABLE #temp
Can someone help explain this to me and resolve it?
http://sqlfiddle.com/#!6/2adc7/9
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tblMobileForms_tblForms". The conflict occurred in database "db_6_2adc7", table "dbo.tblForms", column 'fm_id'.: insert into tblMobileForms(fm_name) values ('lol')
My schema has the ID from tblMobileForms be a foreign key to tblForms.fm_id
To do what you are trying to do you cannot set up the FK on tblMobileForms as an identity. See my fiddle below for more information.
http://sqlfiddle.com/#!6/be6f7/2
Alternatively what you could do is to have tblMobileForms have it's own separate surrogate key and have a different FK column to the tblForms table.
The PK on the tblMobileForms table has the same name as the FK on the same table. Seeing the PK is an IDENTITY column, you can end up with non-matching values.
In my fiddle, the tblForms table contained IDs in the upper 60s. Running the INSERT in the child table would add a record with id 1, which does not exist in the parent table.
I'd create a new row in the tblMobileForms table, and reference that to the parent table.
You could use an INSTEAD OF trigger to apply a random ID to each mobile form as it is inserted:
CREATE TRIGGER dbo.tblMobileForms_Insert
ON dbo.tblMobileForms
INSTEAD OF INSERT
AS
BEGIN
DECLARE #Inserted TABLE (fm_ID INT, fm_html_file VARBINARY(MAX), fm_name NVARCHAR(50));
INSERT #Inserted (fm_ID, fm_html_File, fm_Name)
SELECT fm_ID, fm_html_File, fm_Name
FROM inserted;
IF EXISTS (SELECT 1 FROM #Inserted WHERE fm_ID IS NULL)
BEGIN
WITH NewRows AS
( SELECT fm_ID, fm_html_File, fm_Name, RowNumber = ROW_NUMBER() OVER (ORDER BY fm_name)
FROM #Inserted
WHERE fm_ID IS NULL
), AvailableIDs AS
( SELECT fm_ID, RowNumber = ROW_NUMBER() OVER (ORDER BY fm_ID)
FROM tblForms f
WHERE NOT EXISTS
( SELECT 1
FROM tblMobileForms m
WHERE f.Fm_ID = m.fm_ID
)
AND NOT EXISTS
( SELECT 1
FROM inserted i
WHERE f.fm_ID = i.fm_ID
)
)
UPDATE NewRows
SET fm_ID = a.fm_ID
FROM NewRows n
INNER JOIN AvailableIDs a
ON a.RowNumber = n.RowNumber
IF EXISTS (SELECT 1 FROM #Inserted WHERE fm_ID IS NULL)
BEGIN
RAISERROR ('Not enough free Form IDs to allocate an ID to the inserted rows', 16, 1);
RETURN;
END
END
INSERT dbo.tblMobileForms (fm_ID, fm_html_File, fm_Name)
SELECT fm_ID, fm_html_file, fm_name
FROM #Inserted
END
When each row is inserted the trigger will check for the next available ID in tblForms and apply it sequentially to the inserted rows where fm_id is not specified. If there are no free ID's in tblForms then the trigger will throw an error so a 1 to 1 relationship is maintained (The error would be thrown anyway since tblMobileForms.fm_id is also a PK).
N.b. this requires tblForms.fm_ID to just be an int column, and not identity.
I have got an over 500 rows table with a column called ID which is of datetype INT. Currently the values are all NULL.
What I want to achieve is to populate the ID column with an incremental number for each row, say 1, 2, 3, 4, ..., 500 etc.
Please give me a help with any idea how to achieve this by SQL script.
using ROW_NUMBER in a CTE is one way, but here's an alternative; Create a new id1 column as int identity(1,1), then copy over to id, then drop id1:
-- sample table
create table myTable(id int, value varchar(100));
-- populate 10 rows with just the value column
insert into myTable(value)
select top 10 'some data'
from sys.messages;
go
-- now populate id with sequential integers
alter table myTable add id1 int identity(1,1)
go
update myTable set id=id1;
go
alter table myTable drop column id1;
go
select * from myTable
Result:
id value
----------- -------------
1 some data
2 some data
3 some data
4 some data
5 some data
6 some data
7 some data
8 some data
9 some data
10 some data
While you could also drop and recreate ID as an identity, it would lose its ordinal position, hence the temporary id1 column.
#create one temporary table
CREATE TABLE Tmp
(
ID int NOT NULL
IDENTITY(1, 1),
field(s) datatype NULL
)
#suppose your old table name is tbl,now pull
#Id will be auto-increment here
#dont select Id here as it is Null
INSERT INTO Tmp (field(s) )
SELECT
field(s)
FROM tbl
#drop current table
DROP TABLE tbl
#rename temp table to current one
Exec sp_rename 'Tmp', 'tbl'
#drop your temp table
#write alter command to set identitry to Id of current table
good luck