SQL Server , inserting existing rows into the same table - sql

I have a table say Table A
Col A is the primary key (identity).
Col b is a foreign key from some other table.
Now, for example I want to select the rows where colB = 2 , and insert the rows back into the table again but with a different value of col B say 5 . This can be done easily. Next once the rows are inserted again, I need to find the relation between the copies, especially.
Say new rows are inserted with primary key 6,7,8. Now I want to check which parent row (row with primary key value 1/2/3) has the same data as row with primary key 6. Similarly, I need to find relative for the row with primary key 7, 8. One way is to do the insert one row at a time so that we can say that row with primary key 1 is the copy of row with primary key 6. Another way to do is to join all the columns. I am trying to avoid all these to see if there is any easy solution possible.

Use SCOPE_IDENTITY() to get last primary key inserted value on your table. If another process could be modifying the table then do your update & query in one transaction.

Related

How can I modify the primary key when I deleting a specific row?

Let say I have 7 row in my database and the primary key each row is 1,2,3,4,5,6,7. Now let say I deleted the third row, the primary key each row would be something like this 1,2,4,5,6,7 As you noticed the 3 was removed. I want them like this 1,2,3,4,5,6 the row with a primary key 4 is now become 3 and the 5 is now become 4 and so on.
And another one, let say I deleted the 5th row again with a primary key 5 and then after that the primary key each row would be like this 1,2,3,4,6 Now I want them all like this again 1,2,3,4,5 the row with primary key 6 become now 5. I JUST WANT EVERY TIME I DELETE A ROW I all the primary keys are in orderenter image description here
You can update you primary key column based on row number after the deletion. Attaching sample code considering your table as "customer" and key column is "Cust_id".
update customer cust
JOIN
(
SELECT ROW_NUMBER() OVER (
ORDER BY Cust_id
) row_num, Cust_id
FROM customer
)AS rw_num
ON cust.Cust_ID = rw_num.Cust_ID
set cust.Cust_ID=rw_num.row_num

How to get a count of rows (across tables) dependent on a particular column which is referenced as a foreign key in Postgres

I want to delete a particular row in a table. the id column of that row is used as a foreign key by many tables. How can I get a count of such references to that particular row value of the id column across all tables?
I dont want to do a delete cascade or set null value. So, I want to know if the row to be deleted has something depending upon it or not and if there is nothing depending on that row go ahead with the delete.
table employee has a row with id_employee = 1001, which i want to delete.
id_employee = 1001 occurs in 3 other tables which reference it using a foreign key constraint (checking manually).
How to get the count of same by a select query?

How to insert into a table considering that table has a Primary Key already in it?

I have two tables A and B and need to insert records (few columns not all) from A into B.
Of course I guess I can do:
INSERT INTO B (col2)
SELECT DISTINCT col2
FROM A
However, Col1 in table B (named ID) has a type of INT so it is causing this error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'ID', table 'MyDB.dbo.Visitor'; column does not allow nulls. INSERT fails.
How can I make SQL Server ignore this column and just insert the data I need?
Thanks.
A primary key must fulfill two conditions:
It must be unique in the table (that is, any row in the table can be identified by its primary key), and
The fields that are part of the primary key cannot be NULL. That's because allowing NULL values in the primary key will make the uniqueness of the primary key impossible to hold, because a NULL value is non-equal to any other value, including another NULL.
Quoting from here:
A unique key constraint does not imply the NOT NULL constraint in practice. Because NULL is not an actual value (it represents the lack of a value), when two rows are compared, and both rows have NULL in a column, the column values are not considered to be equal. Thus, in order for a unique key to uniquely identify each row in a table, NULL values must not be used.
This should work assuming you don't insert duplicates into B:
INSERT INTO B (col2)
SELECT DISTINCT col2
FROM A
WHERE col2 IS NOT NULL
Set ID column in table B to "auto-increment".
SQL Server will provide automatically unique values for ID column if you define it as IDENTITY
In your case you can calculate the maximum value of ID column and start IDENTITY from the value that exceeds that maximum.
See the accepted answer for SQL Server, How to set auto increment after creating a table without data loss? for such code.
You need to create a relationship between the two tables and do an update statement.
Update table b set valueb = valuea from table a where a.id = b.id
You also need to rethink your design a little bit it sounds like.

Get Auto foreign key value

I am trying to make generalized master search for my MS-SQL data. Let me explain what I had done till now:
Firstly, I fill one combo box with all the table names.
Then, fill second combo box with columns of selected table from first combo box.
I run general database query like select * from combobox1.text where combobox2.text='someValue'. Everything works fine for me, but I am not able to get foreign key data which is primary in another table.
What i need
suppose Table A has columns: 1 primary key, 2 name of id. And Table 2 with: 1 as primary key column, 2 as address column, and 3 as foreign key column. When I run select * from table2
I get result of foreign key in terms of id, I want value of table1.2 column value.
Why i am asking
This because with this type of system, I can query each and every row in database without manual coding for each table.
Images to explain better
Employee Master Table
Attendance Table
Result i want

primary keys are shifted

Background Information
For some reason, while inserting a huge data into multiple tables from xml, my primary keys are shifted by an offset.. (Maybe because of multiple failed attempts :P)
I have two tables.. tableA and tableB. They are in one-to-may relationship.
tableA is the parent table and has the Primary key column ...say DataIndex.
now DataIndex has come out like this..
685, 686, 687... and so on.
and corresponding values present in the child table i.e TableB are the same.
Problem
How do I shift the values up so that DataIndex start from 1, 2, 3..and so on; In both tables ?
I'm assuming that the primary key is actually an identity column that auto-increments itself upon insertion. What you will need to do is 'reseed' the identity column. You can do this by renaming the table, create a duplicate table with the original name, then inserting the data from the old table to the new one (the primary key field will be reset and will auto-increment from 1 again). When doing the insertion, make sure to include the old primary key value as an additional column for reference in the other tables.
To match up the related table, all you will need to do is do an UPDATE and join to your new table on the old primary key value:
UPDATE tableB SET
PRIMARYKEYCOLUMN = tableA.PRIMARYKEYCOLUMN
FROM tableA
WHERE
tableA.OLDPRIMARYKEYCOLUMN = tableB.PRIMARYKEYCOLUMN
I would do the following:
construct a list of Foreign Keys pointing to your PK;
ALTER all FKs, adding ON UPDATE CASCADE clause. This step might not work for some databases, you might need to DROP and CREATE constraint again;
Find the smallest current PK values, like: SELECT min(id) FROM tableA;
Refresh PK values: UPDATE tableA SET id = id - min_id + 1;
Remove ON UPDATE CASCADE clause.
Note, that depending on the tableA size and the database engine you're using, it might be faster and easier to completely rebuild the table to avoid bloat of data files.
Remove PK
Walk through records eith DB CURSOR or write a script on any language sequentally reading and changing id's
Restore PK
Setup correct identity seed for the PK
Changing seed might involve identity column drop and recreate.