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!
Related
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
This question already has answers here:
Finding a Primary Key Constraint on the fly in SQL Server 2005
(4 answers)
Closed 5 years ago.
I need to drop the primary key of a table Student in a SQL Server database.
I have edited in the table and the script I got is
ALTER TABLE dbo.Student
DROP CONSTRAINT PK__Student__9CC368536561EF8B
But when I run this script in SQL Server query browser to drop the primary key
It shows the message
Msg 3728, Level 16, State 1, Line 1
'PK__Student__9CC368536561EF8B' is not a constraint.
Msg 3727, Level 16, State 0, Line 1
To my concern I think PK__Student__9CC368536561EF8B this will be generated randomly
please help me to drop the primary key constraint using script.
Thanks in advance
You can look up the constraint name in the sys.key_constraints table:
SELECT name
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = Object_id('dbo.Student');
If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:
DECLARE #table NVARCHAR(512), #sql NVARCHAR(MAX);
SELECT #table = N'dbo.Student';
SELECT #sql = 'ALTER TABLE ' + #table
+ ' DROP CONSTRAINT ' + name + ';'
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = OBJECT_ID(#table);
EXEC sp_executeSQL #sql;
This code is from Aaron Bertrand (source).
simply click
'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'
and run the below query is :
Query:alter Table 'TableName' drop constraint PK__TableName__30242045
The answer I got is that variables and subqueries
will not work and we have to user dynamic SQL script. The following works:
DECLARE #SQL VARCHAR(4000)
SET #SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '
SET #SQL = REPLACE(#SQL, '|ConstraintName|', ( SELECT name
FROM sysobjects
WHERE xtype = 'PK'
AND parent_obj = OBJECT_ID('Student')))
EXEC (#SQL)
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 maintain a product that is installed at multiple locations which as been haphazardly upgraded. Unique constraints were added to a number of tables, but I have no idea what the names are at any particular instance. What I do know is the table/columnname pair that has the unique constraints and I would like to write a script to delete any unique constraint on these column/table combinations.
This is SQL Server 2000 and later. Something that works on 2000/2005/2008 would be best!
This script would generate a list of ALTER TABLE..... DROP CONSTRAINT.... commands, which you can then copy+paste and execute (or tweak before executing as needed) to drop all unique constraints / unique indices:
SELECT
'ALTER TABLE ' + OBJECT_NAME(so.parent_obj) + ' DROP CONSTRAINT ' + so.name
FROM sysobjects so
WHERE so.xtype = 'UQ'
I hope it should work on all SQL Server versions from 2000 to 2008 R2.
This is way trickier than it seems like it should be, I found a way that works for me - I believe it will only work on SQL Server 2005 or above. Here's the full scenario:
Table has been created with a unique constraint on a column, ex:
CREATE TABLE table_name (
id bigint identity not null,
column_name varchar(255) not null,
primary key(id),
unique (column_name)
);
Sometime later, it is discovered that this unique constraint is not desired.
INSERT INTO table_name(column_name) VALUES('col1');
results in: Violation of UNIQUE KEY constraint 'UQ__table_na__9FA0BA59160F4887'. Cannot insert duplicate key in object 'dbo.table_name'.
If you have manual control of this db and can running SQL directly on it is possible, just do:
ALTER TABLE table_name DROP CONSTRAINT UQ__table_na__9FA0BA59160F4887;
In my case, these scripts will have been run on different environments and the keys won't have identical names, so in order to remove the constraint I need SQL which takes the table and column name as input and figures out the rest.
DECLARE #table_name nvarchar(256)
DECLARE #col_name nvarchar(256)
DECLARE #Command nvarchar(1000)
-- set your table and column name here:
SET #table_name = N'table_name'
SET #col_name = N'column_name'
SELECT #Command = 'ALTER TABLE ' + #table_name + ' DROP CONSTRAINT ' + d.name
FROM sys.tables t
JOIN sys.indexes d ON d.object_id = t.object_id AND d.type=2 and d.is_unique=1
JOIN sys.index_columns ic on d.index_id=ic.index_id and ic.object_id=t.object_id
JOIN sys.columns c on ic.column_id = c.column_id and c.object_id=t.object_id
WHERE t.name = #table_name and c.name=#col_name
--if you want to preview the generated command before running
SELECT #Command
EXEC sp_executesql #Command;
That removes the unique constraint on the column and allows the insert to proceed.
This page has a quick and dirty way to pull out all the CONSTRAINTs in the database, and from there you could build up dynamic SQL to drop them:
SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT';