Can anyone help me to copy primary key column data into another column of same table?
Example: Student table
ID PK
Name
age
IID
I want to check if IID column is null, then I want it to update with primary key column value of the same table, and looking for some generic way to do this as we have this kind of requirement for multiple tables.
We have other table like this
Dep
DID PK
DNAME
IID
I'm trying but no table to find appropriate way to do this.
Create a stored procedure like the one shown below and pass table name, primary key column name & copy to column name to it. It will create query and execute.
CREATE PROCEDURE [dbo].[UpdateColumnValue]
#tableName as varchar(100),
#copyFromColumnName as varchar(100),
#copyToColumnName as varchar(100)
AS
BEGIN
DECLARE #query as varchar(max);
SET #query = ' UPDATE ' + #tableName +
' SET ' + #copyToColumnName + ' = ' + #copyFromColumnName +
' WHERE ' + #copyToColumnName + ' IS NULL';
EXECUTE(#query);
END
You can add Foreign Key References to the Same Table:
CREATE TABLE DEPT (
ID INT Primary Key,
Name VARCHAR(50),
age INT ,
IID INT FOREIGN KEY REFERENCES DEPT(ID))
By using UPDATE Statement:
UPDATE DEPT
SET IID=ID
WHERE IID IS NULL
Related
I am trying to write a stored procedure in SSMS that creates a table, along with two columns with the subject of the table as the single parameter. The table must be named t followed by the subject of the table. As for the columns, the first column is an auto-incrementing surrogate key ID field (and the primary key) that is named as the subject of the table, followed by ID.
The second column is a natural key which is named as the subject of the table. For instance, a table to be created with the subject being Student would create a table named tStudent, with a StudentID surrogate key column as well as a natural key column named Student. I am trying to do this using a dynamic SQL statement (which I am new to) and keep running into issues while trying to implement my natural key column.
ALTER PROC spCreateTable
#subjectOfTable varchar(50)
AS
DECLARE #dynamicSQL nvarchar(500),
#tableName varchar(50),
#tableID varchar(50);
SET #tableName = ('t' + #subjectOfTable);
SET #tableID = (#subjectOfTable + 'ID');
SET #dynamicSQL = 'CREATE TABLE ' + #tableName + ' ( '+ #tableID + ' INT NOT NULL PRIMARY KEY IDENTITY(1,1) ' + #subjectOfTable + ' VARCHAR(50) ) ';
EXEC (#dynamicSQL)
GO
I can get it to work correctly while just adding the tableID column, but keep having syntax issues with the natural key column subjectOfTable. Someone please help!
I am wondering whether it's possible to create a procedure like
CREATE PROCEDURE GetDummyRow
#table_name VARCHAR(128)
BEGIN
-- ...
END
that inserts into a table with name #table_name a dummy row and returns it from the procedure. Expect that #table_name has a primary key.
For example, if I have a table like
==========================================
Persons
============================================
id | first_name | last_name | spouse_id
============================================
1 | "John" | "Skeet" | 2
2 | "Jane" | "Skeet" | 1
3 | "Bjarne" | "Stroustrup" | NULL
created with
CREATE TABLE Persons
(
id INT AUTO_INCREMEMENT,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
spouse_id INT,
PRIMARY KEY id,
FOREIGN KEY spouse_id REFERENCES Persons.id
)
and I want
DECLARE #t VARCHAR(128);
#t = 'Persons';
EXEC GetDummyRow(#t)
to return
4 | "ASDbaj" | "OEROANkaskoaASDOLJ" | NULL
or
4 | "okasdALAJajdlaLashdasi" | "OEROANkaskoaASDOLJadasd" | 3
for example.
Is there any logical reason why this would be impossible to make?
This can be simplified a lot if you can use default values to specify the values for the dummy row.
CREATE TABLE Persons
(
id INT IDENTITY(1,1) NOT NULL,
first_name VARCHAR(50) NOT NULL DEFAULT 'Dummy',
last_name VARCHAR(50) NOT NULL DEFAULT 'Value',
spouse_id INT
)
GO
CREATE PROCEDURE GetDummyRow (#table_name NVARCHAR(128))
AS
BEGIN
DECLARE #sql nvarchar(MAX)
SET #sql = N'INSERT INTO ' + #table_name + N' DEFAULT VALUES
SELECT * FROM ' + #table_name + N' WHERE id = SCOPE_IDENTITY()'
exec sp_executesql #sql
END
GO
EXEC GetDummyRow 'Persons'
If the values need to be random, you can use NEWID() as the default:
CREATE TABLE Persons
(
id INT IDENTITY(1,1) NOT NULL,
first_name VARCHAR(50) NOT NULL DEFAULT NEWID(),
last_name VARCHAR(50) NOT NULL DEFAULT NEWID(),
spouse_id INT
)
GO
http://sqlfiddle.com/#!3/85776/1
To answer your question, no there is no reason to think this is impossible to make. As commented it could get complicated...
There are a few requirements that are not quite clear. When you say dummy data you do not say random or unique but I am guessing that you would not want the same dummy data for each row. That would require extra coding based on how many data types you want to support.
I would create a cursor based on the table schema. Then while looping through the columns build in code for the data types and constraints / indexes. Is it a primary or foreign key, is it autonumber or is there a check constraint. You can start small and build in exception handling for table/columns that do not fit the most anticipated types.
Depending on the architecture and complexity of your database you can take advantage of things like autonumbered primary keys.
If there is a foreign key you can either choose a key from the referenced table at random (ie. Top 1 ... From) or call the procedure recursively to insert a dummy record in that table and return the new key. This would require putting most of the functionality in an inner procedure that returns a primary key and a wrapper that returns the result set you are looking for.
I believe these links will be a good start, looking up the topics will lead to other examples.
https://msdn.microsoft.com/en-us/library/ms186778.aspx
https://msdn.microsoft.com/en-us/library/ms177862.aspx
I am creating a sample database with two tables submissions and submittedItems. I am populating this table with sample data and I wanted to know how to populate the second table with the primary key from the first table.
The script I have works fine for what I am testing however I am currently inserting the foreign key by simply mirroring the count. Since this is a new table it works fine as both start with the same number. Where my question is what if the table already had data within it, How would I go about retrieving the PK of the last record entered into the submissions table? I know when using Identity I could use SELECT SCOPE_IDENTITY() to get the last identity entered but not sure of the proper select statement to use for anything else. OR am I misunderstanding the use of Scope_Identity() and it does retrieve whatever the last PK/Identity that was entered? As you can see I am no expert at sql so if there is a better approach I would welcome any suggestions.
Thanks in advance,
use SampleRecords
GO
--create two test tables
CREATE TABLE submissions
(submission_id int Identity(1,1) primary key not null,
submissionName varchar(150),
dateSubmitted datetime)
CREATE TABLE submissionItems
(submissionitems_id int identity(1,1) primary key,
fk_submission_id int not null,
item varchar(150),
CONSTRAINT fk_submission_id foreign key (fk_submission_id) references submissions (submission_id))
--populate tables with sample data
DECLARE #totalRecords int
SET #totalRecords = 0
DECLARE #currentKey int
WHILE #totalRecords < 500
BEGIN
SET #totalRecords = #totalRecords + 1
INSERT INTO dbo.submissions (submissionName, dateSubmitted)
VALUES
('submission record ' + cast(#totalRecords AS varchar(3)), SYSDATETIME())
INSERT INTO dbo.submissionItems (fk_submission_id, item)
VALUES
(#totalRecords, 'a new record item for submission '+ cast(#totalRecords AS varchar(3)))
-- I tried using scope_identity as follows but could not get the syntax correct
-- ('submission record ' + cast(Select Scope_Identity() AS varchar(3)), SYSDATETIME())
END
Yes, just use the ScopeIdentity...
--populate tables with sample data
DECLARE #totalRecords int
SET #totalRecords = 0
DECLARE #currentKey int
WHILE #totalRecords < 500
BEGIN
SET #totalRecords = #totalRecords + 1
INSERT INTO dbo.submissions (submissionName, dateSubmitted)
VALUES ('submission record ' + cast(#totalRecords AS varchar(3)), SYSDATETIME())
Set #currentKey = Scope_Identity()
INSERT INTO dbo.submissionItems (fk_submission_id, item)
VALUES (#currentKey, 'a new record item for submission '+ cast(#totalRecords AS varchar(3)))
END
I am trying to add a clustered index to an existing table in SQL Server 2008, and it needs to be an automated script, because this table exists on several databases across several servers.
In order to add a clustered index I need to remove the PK constraint on the table, and then re-add it as unclustered. The problem is the name of the PK constraint is auto-generated, and there is a guid appended to the end, so it's like "PK_[Table]_D9F9203400."
The name is different across all databases, and I'm not sure how to write an automated script that drops a PK constraint on a table in which I don't know the name of the constraint. Any help is appreciated!
UPDATE:
Answer below is what I used. Full script:
Declare #Val varchar(100)
Declare #Cmd varchar(1000)
Set #Val = (
select name
from sysobjects
where xtype = 'PK'
and parent_obj = (object_id('[Schema].[Table]'))
)
Set #Cmd = 'ALTER TABLE [Table] DROP CONSTRAINT ' + #Val
Exec (#Cmd)
GO
ALTER TABLE [Table] ADD CONSTRAINT PK_Table
PRIMARY KEY NONCLUSTERED (TableId)
GO
CREATE UNIQUE CLUSTERED INDEX IX_Table_Column
ON Table (Column)
GO
You can look up the name of the constraint and write a bit of dynamic SQL to handle the drop.
SELECT name
FROM sys.key_constraints
WHERE parent_object_id = object_id('YourSchemaName.YourTableName')
AND type = 'PK';
I need help in auto populating the primary key values in foreign key table while inserting data in foreign key table. For Example: I have created table:
create table Patient
(
PatientId int IDENTITY(1,1) primary key,
FirstName varchar(50),
SurName varchar(50),
Gender char(20),
)
Say 5 rows are there in this Patient Table:
Say First Row value is: 1, Priya, Kumari, Female
I have created the Guardians Table:
create table Guardians
(
GuardiansId int identity(1,1) primary key,
PatientId int foreign key references Patient(PatientId),
FirstName varchar(50),
SurName varchar(50),
Gender char(20),
RelationToPatient varchar(50),
)
In this table Insert operations are like this:
insert into Guardians(FirstName, SurName, Gender,RelationToPatient)values('Sumit','Kumar','Male','Wife')
While selecting the Guardians Table PatientId showing NULL values: My query is while inserting the values in Guardians Table PatientId should be auto Populated which will come from Patient Table...
My second problem is: How to create the Identity column as varchar. For example: suppose I want to increment my Guardians Table with 'GRD0001', 'GRD0002', 'GRD0003' like this...
Thanks,
S.D
Your question is not very clear - what exactly do you want to do??
When you insert something into the Guardians table, you want to automatically also insert it into the Patients table? I don't quite follow. Can you make a complete example, maybe??
If you need to capture the insert IDENTITY value from the Patient table, do this:
DECLARE #NewPatientID INT
INSERT INTO dbo.Patient(fields) VALUES(.......)
SET #NewPatientID = SCOPE_IDENTITY()
INSERT INTO dbo.Guardians(PatientId, ......) VALUES(#NewPatientID, ......)
As for your second question: leave you GuardiansId IDENTITY as it is (only an INT column can be an IDENTITY and you want to keep that - trust me!) and add a computed column to your table:
ALTER TABLE dbo.Guardians
ADD GuardianIDWithPrefix AS
'GDR' + RIGHT('0000' + CAST(GuardiansId AS VARCHAR(4)), 4) PERSISTED
Since it's a PERSISTED field, you can even index on it and use it like a normal field in every respect.
That should do the trick!