I can't find the right syntax to rename a table in T-SQL when the table name contains an ']' character.
It seems like the sp_rename procedure doesn't use the same escaping rules as T-SQL DDL.
How can this be done?
CREATE SCHEMA MySchema
CREATE TABLE [MySchema].[MyTab]]le5](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[SomeField] [bigint] NULL,
[MyField] [nvarchar](4000) NULL)
EXEC sp_rename 'MySchema.MyTa]ble5', 'MyTable6'
Use the same syntax as CREATE TABLE...
EXEC sp_rename 'MySchema.[MyTab]]le5]', 'MyTable6'
Or rely on SET QUOTED_IDENTIFIER ON and a different delimiter
EXEC sp_rename 'MySchema."MyTab]le5"', 'MyTable6'
Related
It happens when i run this code:
CREATE TABLE distributors (
did integer PRIMARY KEY DEFAULT nextval('serial'),
name varchar(40) NOT NULL CHECK (name <> '')
);
I have tried remover the nextval('serial') but to no avail
You want to do this:
CREATE TABLE distributors (
did serial PRIMARY KEY DEFAULT,
name varchar(40) NOT NULL CHECK (name <> '')
);
The serial type is actually a macro. That per docs (Serial) does:
CREATE SEQUENCE tablename_colname_seq AS integer;
CREATE TABLE tablename (
colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
Assuming you are on a recent version(10+) of Postgres generated always as identity(see Create Table) is the preferred alternative these days.
nextval('someseries') relies on having an existing series. You can create that with:
CREATE SEQUENCE someseries;
When you removed the nextval, you probably still had the DEFAULT keyword there, which expects a value afterward to define what the default for the column is.
I have a foreign key constraint on my table created using the following command in db2
ALTER TABLE "ADDRESS" ADD FOREIGN KEY("CITY_ID") REFERENCES CITY("ID");
Now I am trying to drop the constraint. Since there was no name given to the constraint while creating, the alter command to drop the foreign key does not work.
Can I use a select command inside the alter table command so that I can query the SYSCAT.TABCONST table to get the constraint id?
Something like
ALTER TABLE ADDRESS DROP FOREIGN KEY
(SELECT CONSTNAME FROM SYSCAT.TABCONST where tabname='ADDRESS' and TYPE='F')
--#SET TERMINATOR #
BEGIN
EXECUTE IMMEDIATE (SELECT 'ALTER TABLE '||TABSCHEMA||'.'||TABNAME||' DROP CONSTRAINT '||CONSTNAME FROM SYSCAT.REFERENCES WHERE TABSCHEMA=USER AND TABNAME='ADDRESS' AND REFTABSCHEMA=USER AND REFTABNAME='CITY');
END#
Note that there may be multiple ADDRESS -> CITY references. But this will work if there is only one such a foreign key between these tables.
We assume here that both tables are in the current user's schema.
You can use compound SQL for this. Here is an example:
--#SET TERMINATOR #
begin
declare v_fkname varchar(128) default '';
declare v_sql varchar(1024);
declare v_not_found integer default 0;
declare not_found condition for sqlstate '02000';
declare continue handler for not_found set v_not_found=1 ;
set v_fkname = (select constname from syscat.tabconst where tabname='ACTORS' and tabschema='USER1' and type='F');
if v_not_found = 0
then
set v_sql='ALTER TABLE actors DROP FOREIGN KEY '||v_fkname ;
execute immediate(v_sql);
end if;
end#
Remember that you will also need to verify afterwards that no objects have become invalid as a result of this change.
Adding tSQLt tests to an existing production product, so we're not able to alter tables, constraints, etc. Currently all the constraints are labeled like 'PK_dbo.ViolationCategory' when they should be like 'PK_ViolationCategory'
When I run:
EXEC tSQLt.NewTestClass 'AdHocReportFiltersTestConstraint';
GO
CREATE PROCEDURE [AdHocReportFiltersTestConstraint].[Setup]
AS
BEGIN
EXEC tSQLt.FakeTable 'dbo.AdHocReports'
END
GO
CREATE PROCEDURE [AdHocReportFiltersTestConstraint].[test_AdHocReportFilters_Constraint]
AS
BEGIN
DECLARE #Id uniqueidentifier = NEWID()
DECLARE #Name NVARCHAR(Max) = 'Test_Name'
DECLARE #Value NVARCHAR(Max) = 'Test_Value'
DECLARE #AdHocReport_ID uniqueidentifier = NEWID()
INSERT INTO dbo.AdHocReportFilters ([Id], [Name], [Value], [AdHocReport_Id])
VALUES (#Id, #Name, #Value, #AdHocReport_ID)
exec tSQLt.ApplyConstraint 'dbo.AdHocReports', 'PK_dbo.AdHocReportFilters';
END
EXEC tSQLt.RunTestClass 'AdHocReportFiltersTestConstraint';
GO
I receive the error,
(1 row affected)
[AdHocReportFiltersTestConstraint].[test_AdHocReportFilters_Constraint] failed:
(Error) The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_dbo.AdHocReportFilters_dbo.AdHocReports_AdHocReport_Id". The conflict occurred in
database "CR", table "dbo.tSQLt_tempobject_fbc9c8bf09e742929eccae914d5e440d",
column 'Id'.[16,0]{test_AdHocReportFilters_Constraint,11}
Any ideas of how to work around this?
Once I get this working, I will add a second record to violate the PK constraint and catch the error.
Just looking at your code, I see you are doing the following:
Fake the table dbo.AdHocReports
Insert a row into the table dbo.AdHocReportFilters
Apply a PK constraint called "PK_dbo.AdHocReportFilters" to the table dbo.AdHocReports
You will then try and add another row to validate the PK_dbo.AdHocReportFilters constraint
The error you are getting appears to to suggest that you are violating a foreign key on the AdHocReportFilters table - which is expected since that table hasn't been faked.
It is not clear from the test name whether you are trying to validate the behaviour of the primary key or foreign key.
Looking at the steps, I think you may be mixing up the two tables but without more detailed code (i.e. CREATE TABLE) statements, it is difficult for me to help you further.
There are two tables:
dbo.AdHocReports (Id,... (more columns))
dbo.AdHocReportFilters ([Id], [Name], [Value], [AdHocReport_Id] )
AdHocReportFilters.AdHocReport_Id is foriegn key for table dbo.AdHocReportFilters referencing dbo.AdHocReports.Id
When you are inserting insert a row in table AdHocReportFilters, you should make sure AdHocReportFilters.AdHocReport_Id is an id column in table dbo.AdHocReports
But in your SP, #AdHocReport_ID is NEWID(), which is of course a unique value and hence not in table dbo.AdHocReports.Id
Work around,
Disable foreign key contraint
ALTER TABLE dbo.AdHocReportFilters NOCHECK CONSTRAINT FK_dbo.AdHocReportFilters_dbo.AdHocReports_AdHocReport_Id
I am new to SQL and am attempted to create a table, then alter the table to add some constraints with ALTER and finally insert 2 employees, one managing the other.
I have been getting this error in pgAdmin4 "ERROR: syntax error at or near "INSERT"
If anyone could let me know any other obvious issues in my code that would be great
Here is the table:
CREATE TABLE employee (
emp_id integer NOT NULL,
first_name varchar(15) NOT NULL,
last_name varchar(15) NOT NULL,
manager integer
);
And the altering:
ALTER TABLE employee ADD CONSTRAINT unique_emp_id UNIQUE (emp_id);
ALTER TABLE employee ADD FOREIGN KEY (manager) REFERENCES emp_id;
ALTER TABLE employee ADD CHECK (emp_id != manager)
INSERT INTO employee VALUES
(1, 'Tom', 'Jones', 2);
INSERT INTO employee (emp_id, first_name, last_name)
VALUES (2, 'Dave', 'Smith');
The foreign key reference needs to mention the table, even for a self-reference:
ALTER TABLE employee ADD FOREIGN KEY (manager) REFERENCES employee(emp_id);
In addition, the first insert doesn't work because the table is empty, so the foreign key fails. The inserts are in the wrong order. You should also list all the columns for an insert, even when you think you know them.
Here is a SQL Fiddle with the rest of the statements working.
I created a table in PostgreSQL like this:
CREATE TABLE Table1 (
Id varchar(100) PRIMARY KEY CHECK (Id ~ '^[a-z0-9]{3,15}$'),
...
);
This will automatically create a constraint called table1_id_check.
Now I would like to change the check constraint to
(Id ~ '^[a-z0-9]{3,}$')
How can I do this in PostgreSQL as a single statement without dropping the constraint and recreating it again?
Using multiple statements within a transaction works on all SQL dbms that support using this DDL in a transaction.
begin transaction;
alter table table1
drop constraint table1_id_check;
alter table table1
add constraint table1_id_check CHECK (Id ~ '^[a-z0-9]{3,}$');
commit;
PostgreSQL lets you use multiple clauses within an ALTER TABLE statement.
alter table table1
drop constraint table1_id_check,
add constraint table1_id_check CHECK (Id ~ '^[a-z0-9]{3,}$');