Syntax To Add 2 Constraints Using Alter Table?

Jul 20, 2005

Just started learning SQL recently.

But one thing i'm still not clear on is about altering relationships between
tables after they've been created.

Instead of creating a foreign key when the table is first created - i create
the table and then run a query to set the foreign key and relationship
(one-to-one, one-to-many etc)

Anyways, long story short is i want to create a one-to-one relationship with
a table but am having problems with adding more than one constraint at a
time when altering a table.

Understand yet? Easiest thing to do is show you:

I have 2 tables: Branch_Table and Employee_Table

I want to create a one-to-one relationship between emp_id on the
Branch_Table and manager_id on the Employee_Table.

The SQL i've written which doesn't seem to work is:

ALTER TABLE Branch_Table
Add Constraint Branch_Table_FK1 FOREIGN KEY (manager_id)
Add Constraint Branch_Table_UQ1 Unique (manager_id)
References Employee_Table (emp_id));

Am having trouble with that second Add constraint (UQ1 unique). I know it's
something to do with the Add syntax above.

So basically, my question is can i create a one-to-one relationship with
just the one SQL Query? And how would i do it?

Many thanks in advance.

View 6 Replies


ADVERTISEMENT

Alter Table Syntax

Aug 1, 2001

I keep getting a syntax error when I try to execute the following statement from Query Analyzer:

Alter Table Table1
Alter Column Field1 Int

I am getting the following error:
Server: Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near 'column'.

I am converting Field1 from a varchar to int, is this not allowed?

TIA,

Chris

View 2 Replies View Related

Problem With ALTER TABLE Syntax

Jul 1, 2005

I finally found a way to "deploy" my local SqlServerExpress (SSE) database to the remote Sql2K server... In VisualWebDeveloper (VWD) I can create the table definition and then save the creation sql script and use that in SSE Express Manager while connected to my remote DB. I am describing this because I'm so surprised no one has had problems with this as thousands of developers, some very unexperienced (as me maybe!), are trying the same situation now that some are offering 2.0 hosting... Well I thought this was a great idea until the Sql2K server is returning error messages on the script VWD created. So please could you help since I'm not that good at complex sql scripting. It seems the error comes from the ALTER TABLE syntax:BEGIN TRANSACTIONSET QUOTED_IDENTIFIER ONSET ARITHABORT ONSET NUMERIC_ROUNDABORT OFFSET CONCAT_NULL_YIELDS_NULL ONSET ANSI_NULLS ONSET ANSI_PADDING ONSET ANSI_WARNINGS ONCOMMITBEGIN TRANSACTIONCREATE TABLE dbo.Table2 ( prID int NOT NULL IDENTITY (1, 1), DateInserted datetime NOT NULL, Title nvarchar(100) NOT NULL, Description nvarchar(MAX) NULL, CategoryID smallint NOT NULL, DateLastUpdated datetime NULL, Price int NOT NULL, SpecialPrice int NULL, ImgSuffix nvarchar(5) NULL, ImgCustomWidth smallint NULL )  ON [PRIMARY]  TEXTIMAGE_ON [PRIMARY]GOALTER TABLE dbo.Table2 ADD CONSTRAINT PK_Table2 PRIMARY KEY CLUSTERED ( prID ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GOCOMMIT

View 2 Replies View Related

Syntax Error ALTER TABLE

Jul 25, 2006

HiHaving a problem with a ms sql 2000 server. The script below wascreated i SQL manager 2005 lite and gives a syntax error near '('ALTER TABLE [dbo].[Community_ActivityLog]ADD CONSTRAINT [PK_Community_Errors]PRIMARY KEY CLUSTERED ([activity_ID])WITH (PAD_INDEX = OFF,IGNORE_DUP_KEY = OFF,STATISTICS_NORECOMPUTE = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON)ON [PRIMARY]GOAny ideas of what might be wrong?/Michael

View 1 Replies View Related

Syntax Error With "alter Table" Statement

Mar 27, 2001

Folks!

What is wrong with my syntax with the following command?:

alter table EmployeeInfo alter column OriginDate smalldatetime not null default getdate()

I'm getting:

Incorrect syntax near the keyword 'default'

Currently, in my table OriginDate is nullable with no default.
Thanks in advance for your help!

APF

View 2 Replies View Related

How Do I Alter Column With Constraints ?

Nov 22, 2007



I have about 100 databases which yeterday had the wrong ddl for a column added, we have a simple cursor that loops through all databases on the server and runs the sql statement.

The following was run

ALTER TABLE salesrep ADD newCol bit DEFAULT 1

Problem is that it should have been this (and preferably have had a named constraint):


ALTER TABLE salesrep ADD newCol bit NOT NULL DEFAULT 0





Problem is now i dont know the names of the contraints they have random hex on the end "The object 'DF__SALESREP__newCol__5BCD9859' is dependent on column..."


How do i just drop this column with ANY constraints on it?,

I really dont want to go through the databases 1 by 1 and look up the constraint name then drop the constraint, then drop the column so i can add it in correctly.


I wish the following would just work.

ALTER TABLE salesrep ALTER COLUMN newCol bit NOT NULL Default 0





View 1 Replies View Related

Alter Table Syntax Error - Anyone Sees The Error?

Nov 24, 2004

Hello,

the following alter table statement:

ALTER TABLE [dbo].[CalCalendar]
ALTER COLUMN [OID] uniqueidentifier NOT NULL PRIMARY KEY NONCLUSTERED

is answered with:

Server: Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'PRIMARY'.

which I consider to be interesting. Anyone has an idea why? I checked documentation but I do not see an error.

Note that:

ALTER TABLE [dbo].[CalCalendar]
ALTER COLUMN [OID] uniqueidentifier NOT NULL

DOES get executed, and

ALTER TABLE [dbo].[CalCalendar]
ALTER COLUMN [OID] uniqueidentifier NOT NULL PRIMARY KEY

produces the same error.

Now, in my understanding this has nothing to do with an index may already exist etc. - the eror indicates a SYNTAX error, before any checking. Makes no sense to me, though, reading the documentation.

So - anyone an idea?

View 4 Replies View Related

Alter Table Alter Column In MSACCESS. How Can I Do It For A Decimal Field?

Jul 23, 2005

Hi people,I?m trying to alter a integer field to a decimal(12,4) field in MSACCESS 2K.Example:table : item_nota_fiscal_forn_setor_publicofield : qtd_mercadoria integer NOT NULLALTER TABLE item_nota_fiscal_forn_setor_publicoALTER COLUMN qtd_mercadoria decimal(12,4) NOT NULLBut, It doesn't work. A sintax error rises.I need to change that field in a Visual Basic aplication, dinamically.How can I do it? How can I create a decimal(12,4) field via script in MSACCESS?Thanks,Euler Almeida--Message posted via http://www.sqlmonster.com

View 1 Replies View Related

INCORRECT SYNTAX NEAR STRING FOR ALTER SQL

Oct 20, 2007

HELP
I am trying to create a new column for every file in a folderbut i keep getting an sql exception  - incorrect syntax near ' whatever the value of the file name is'it works if i just type in the value directlymy code look like this
 fsofolder = CreateObject("Scripting.FileSystemObject")
        folder = fsofolder.GetFolder("the path to the Files")
        files = folder.Files
        For Each objfile In files
            sname = objfile.Name
                  
            cmd3.CommandText = "ALTER TABLE NEW ADD " & "' " & sname & " ' " & " nvarchar(MAX)"

            DatabaseConnection.Open()

            Try

                cmd3.Connection = DatabaseConnection
                cmd3.ExecuteNonQuery()
            Catch ex As SqlException
                MsgBox(ex.Message)
            End Try

            DatabaseConnection.Close()

View 10 Replies View Related

ALTER LOGIN Syntax Problem

Oct 30, 2007



I typed the following in sqlcmd:

1> ALTER LOGIN [BUILTINAdministrators] WITH DEFAULT_DATABASE=master
2> GO


And I got this error:
Line 1: Incorrect syntax near 'LOGIN'.

Can you help me find the problem? Thanks

View 6 Replies View Related

Alter Table Alter Column

Jul 20, 2005

I would like to add an Identity to an existing column in a table using astored procedure then add records to the table and then remove the identityafter the records have been added or something similar.here is a rough idea of what the stored procedure should do. (I do not knowthe syntax to accomplish this can anyone help or explain this?Thanks much,CBLCREATE proc dbo.pts_ImportJobsas/* add identity to [BarCode Part#] */alter table dbo.ItemTestalter column [BarCode Part#] [int] IDENTITY(1, 1) NOT NULL/* add records from text file here *//* remove identity from BarCode Part#] */alter table dbo.ItemTestalter column [BarCode Part#] [int] NOT NULLreturnGOSET QUOTED_IDENTIFIER OFFGOSET ANSI_NULLS ONGOhere is the original tableCREATE TABLE [ItemTest] ([BarCode Part#] [int] NOT NULL ,[File Number] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULLCONSTRAINT [DF_ItemTest_File Number] DEFAULT (''),[Item Number] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULLCONSTRAINT [DF_ItemTest_Item Number] DEFAULT (''),[Description] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULLCONSTRAINT [DF_ItemTest_Description] DEFAULT (''),[Room Number] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULLCONSTRAINT [DF_ItemTest_Room Number] DEFAULT (''),[Quantity] [int] NULL CONSTRAINT [DF_ItemTest_Quantity] DEFAULT (0),[Label Printed Cnt] [int] NULL CONSTRAINT [DF_ItemTest_Label Printed Cnt]DEFAULT (0),[Rework] [bit] NULL CONSTRAINT [DF_ItemTest_Rework] DEFAULT (0),[Rework Cnt] [int] NULL CONSTRAINT [DF_ItemTest_Rework Cnt] DEFAULT (0),[Assembly Scan Cnt] [int] NULL CONSTRAINT [DF_ItemTest_Assembly Scan Cnt]DEFAULT (0),[BarCode Crate#] [int] NULL CONSTRAINT [DF_ItemTest_BarCode Crate#] DEFAULT(0),[Assembly Group#] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULLCONSTRAINT [DF_ItemTest_Assembly Group#] DEFAULT (''),[Assembly Name] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULLCONSTRAINT [DF_ItemTest_Assembly Name] DEFAULT (''),[Import Date] [datetime] NULL CONSTRAINT [DF_ItemTest_Import Date] DEFAULT(getdate()),CONSTRAINT [IX_ItemTest] UNIQUE NONCLUSTERED([BarCode Part#]) ON [PRIMARY]) ON [PRIMARY]GO

View 2 Replies View Related

Alter Table Alter Column...

Oct 8, 2007

I am using sql server ce.I am changing my tables sometimes.how to use 'alter table alter column...'.for example:I have table 'customers', I delete column 'name' and add column 'age'.Now I drop Table 'customers' and create again.but I read something about 'alter table alter column...'.I use thi command but not work.I thing syntax not true,that I use..plaese help me?



my code:
Alter table customers alter column age

View 7 Replies View Related

TSQL - Using ALTER TABLE - ALTER COLUMN To Modify Column Type / Set Identity Column

Sep 7, 2007

Hi guys,
If I have a temporary table called #CTE
With the columns
[Account]
[Name]
[RowID Table Level]
[RowID Data Level]
and I need to change the column type for the columns:
[RowID Table Level]
[RowID Data Level]
to integer, and set the column [RowID Table Level] as Identity (index) starting from 1, incrementing 1 each time.
What will be the right syntax using SQL SERVER 2000?

I am trying to solve the question in the link below:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2093921&SiteID=1

Thanks in advance,
Aldo.

I have tried the code below, but getting syntax error...



ALTER TABLE #CTE
ALTER COLUMN
[RowID Table Level] INT IDENTITY(1,1),
[RowID Data Level] INT;


I have also tried:

ALTER TABLE #CTE
MODIFY
[RowID Table Level] INT IDENTITY(1,1),
[RowID Data Level] INT;







View 18 Replies View Related

UGH! Failed To Enable Constraints. One Or More Rows Contain Values Violating Non-null, Unique, Or Foreign-key Constraints.

Jan 9, 2007

I know this is probably a flick of a switch but I cannot figure out which switch.  Setup is SQL Server / Stored Procedures / DAL / BLL(skipped for testing) / PL.  The stored procedure queries from only one table and two columns are ignored because they are being phased out.  I can run the stored procedure and preview the data in the DAL but when I create a page with an ODS linked to the DAL and a GridView I get this error.  I checked every column that does not allow nulls and they all have values.  I checked unique columns (ID is the only unique and is Identity=Yes in the table definition).  I checked foreign-key columns for values that are not in the foreign table and there are none.  Any ideas why do I get this? 
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

View 3 Replies View Related

Failed To Enable Constraints. One Or More Rows Contain Values Violating Non-null, Unique, Or Foreign-key Constraints.

Jan 17, 2008

Hi,
    I am getting the above error when trying to load a report into my Web Application, I have tracked the error down to one specific field in my database. Even though this field is a NVarChar field and is of size 30 it would seem that  there is an issue returning the value from the field. I can write it into the database no problems but when I try to get it out of the database it returns the above error.
e.g
MOB 401.908.804 - Fails
0401.907.324 - okay
8239 9082 (pager) - fails
Anyone got an idea on how to fix this????
Regards..
Peter.

View 7 Replies View Related

Alter Column Results In Incorrect Syntax Near 'column'

Oct 29, 2001

I ran this query against the pubs database and it runs successfully

ALTER TABLE publishers ALTER COLUMN state CHAR(25)

I change the table & field names for my db as follows:
ALTER TABLE customquery ALTER COLUMN toclause CHAR(25)

and run against my database and I get the following error - Incorrect syntax near 'COLUMN'.

My column name is correct - I don't know why it would run fine against pubs, but not my db. I do not have quoted identifiers turned on. I have tried using [] around my column name [toclause], but that didn't change anything. Any help would be appreciated.
Thanks.

View 1 Replies View Related

Table Constraints

Sep 25, 2002

Can anyone recommend a good article/book on the subject? I am trying to find out more about compound primary keys. How many is “too many”? Does the number of primary key columns affect your performance? If so, how does it affect it? Should some of the constraints be handled from stored procedures?

Any response is greatly appreciated.

:cool:

View 2 Replies View Related

How To Get All The Constraints On A Table

Jul 28, 2006

Hi,

I am new to MsSql. I want to know is there any command through which we can get all the consraints on a table or in a databases. In the same way how to get the all table names in a database from the coomand prompt or thorugh query analyzer.

Thanks

View 4 Replies View Related

Table Constraints

Aug 11, 2006

Hi all

Is there anyway you can deactivate/enable all constraints on a particular table so it can be done in a script?

Thanks.

View 7 Replies View Related

Transact SQL :: How To Alter Existing Table Column As Identity Without Dropping Table

Nov 20, 2013

I have created a table as below mentioned. Then I want to alter the ID column as identity(1,1) without dropping the table as well as losing the data.

create table dbo.IdentityTest
(
id int not null,
descript varchar(255) null,
T_date datetime not null
)

View 7 Replies View Related

Transact SQL :: Dynamically Alter Schema Of Stage Table When Source Table Structure Changed?

Oct 25, 2015

we have a table in our ERP database and we copy data from this table into another "stage" table on a nightly basis. is there a way to dynamically alter the schema of the stage table when the source table's structure is changed? in other words, if a new column is added to the source table, i would like to add the column to the stage table during the nightly refresh.

View 4 Replies View Related

Table Constraints Question

Feb 22, 2008

Does anybody know how to query for the table constraints, indexes etc..

I believe there are sys tables that contain these but I'm not familiar with them any help would be appreciated.

View 4 Replies View Related

Viewing A Table's Constraints?

Apr 10, 2008

This is an SQL Server 2000 question. Without having access to the "Design Table" option in the pop-up menu of a table, is there another way to see what constraints, indexes, primary key, etc. that a table has?

Thank you.

View 4 Replies View Related

Copy Table With Constraints

Nov 29, 2007



I'm trying to find a Stored procedure that will perform a complete table copy from the source to the target.

Anyone have one?

View 4 Replies View Related

How To Alter The Table With Delete/update Cascade Without Recreating The Table

Jul 26, 2004

I have contract table which has built in foreign key constrains. How can I alter this table for delete/ update cascade without recreating the table so whenever studentId/ contactId is modified, the change is effected to the contract table.

Thanks


************************************************** ******
Contract table DDL is

create table contract(
contractNum int identity(1,1) primary key,
contractDate smalldatetime not null,
tuition money not null,
studentId char(4) not null foreign key references student (studentId),
contactId int not null foreign key references contact (contactId)
);

View 3 Replies View Related

How To Alter Column Length Of The Master Table Along With The Slave Table?

Aug 13, 2006

In SQL Server 2005,here are two tables, created by the following SQL Statements:

CREATE TABLE student(
ID CHAR(6) PRIMARY KEY,
NAME VARCHAR(10),
AGE INT
);

CREATE TABLE score(
ID CHAR(6) PRIMARY KEY,
SCORE INT,
FOREIGN KEY(ID) REFERENCES student(ID)
);

For the length of Column ID is not enough, So I want to alter its length.The alter statement is:

ALTER TABLE student ALTER COLUMN ID CHAR(20)

For the table student is referenced by table score, the alter statement can not alter the column of the table student, and the SQL Server DBMS give the errors.

But, I can manually alter the length of the column ID in SQL SERVER Management Studio. How to alter column length of the master table(student) along with the slave table(score)?

Thanks!

View 2 Replies View Related

SQL Server 2008 :: Alter Table Triggers Recreate Table?

May 26, 2015

which ALTER TABLE/ALTER COLUMN- Statement has a Recreate Table as result ?

View 2 Replies View Related

Table Constraints To XML In SQL-Server 2000

Aug 4, 2006

Hi,
I am DB programmer, How can i get Table Constraints to XML in SQL-Server 2000 with out data.

View 1 Replies View Related

How Do I View Table Information Such As Constraints?

Sep 19, 2007

I remember once using a command in Query Analyser that gave me all theinformation about a table. It showed details about the columns,constraints, keys, indexes etc.I can't remember how I did this? Can anyone help me?It could of been a stored proc that I called or a query on the systemtables.I do know that it was very simple to do and it was executed in QueryAnalyser.Can anyone help me?

View 2 Replies View Related

Table Valued Function And Constraints

May 29, 2008



Is it possible to define a constraint for Primary Key on more than 1 column or an alternate index on a column in a return table from an inline table valed function?

Example Header:


alter FUNCTION [dbo].[fntMetaFrame] (@ii_CompanyID int)

RETURNS @tbl_MetaFrame TABLE ( pk_Key int Identity(1,1) primary key,






ObjectID int ,







Seq int null )




I want the primary key to be pk_Key, ObjectID

OR

I want to add another index on ObjectID.

View 6 Replies View Related

How To Modify Colum (alter Table) Of Table That Is Replicated?

Jul 20, 2005

Hello!I have an MS SQL-server with an database, that runs replication. In thisdatabase there is an table with an columni want to extend; varchar(50)->varchar(60).But I get this error (using design window of Enterprise Manager): Cannotdrop the table 'MytableName' because it is being used for replication.Thanks for helpBjoern

View 1 Replies View Related

ALTER TABLE SWITCH PARTITION On A Replicated Table

Apr 10, 2007

A customer wants to implement table partitioning on a replicated table.



They want to hold 13 months of data in the table and roll off the earliest/oldest month to an identical archive table. The table has a date field and partitioning by month makes sense all around.



So SWITCH PARTITION is the obvious solution to this, except for the fact that the table is replicated (transactional w/no subscriber updates).



What are his architectural or practical solutions to using table partitioning and replication?











thx

View 5 Replies View Related

DB Engine :: Migrate Table Data When Dealing With Constraints

Nov 19, 2015

I need to script out data in several tables (30+) and then reload those tables on a different database.  The "target" database table data will get overwritten each time, not appended to.  Several of these tables have numerous foreign keys and other constraints that must be dealt with.  None of them have more than 100 records or so.  Then I need to keep this script in source control and reference it as part of a post-deployment step with a Visual Studio DB project.

I have redgate, dbghost and visual studio.  Are there any tools will generate the script for me complete with dropping all the constraints, truncating the tables, then re-adding the constraints back?  Or, am I looking at simply scripting the table data out, then modifying the script myself to add in the steps to drop/readd the constraints?  Further, since some of these tables might have relationships, not just to other tables, but to those in question, there will likely be an order in which the tables need to get loaded.

The approach I am thinking will be needed, since ive done this sort of thing before except with SSIS, is to run something like dbghost or the "generate scripts" option in SSMS as a starting point.  From there, change the order around as needed, etc.  

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved