Alter Table And Column Order

Jul 20, 2005

Is it possible to add a column to a table using the "alter table"
statement and specify where in the sequence of columns the new column
sits. If not is there any way to alter the order of columns using TSQL
rather than Enterprise Manager / Design Table.

TIA

Laurence Breeze

View 2 Replies


ADVERTISEMENT

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

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

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

ALTER TABLE DROP COLUMN LastUpdated Failed Because One Or More Objects Access This Column.

Mar 7, 2008

Hi I’m trying to alter a table and delete a column I get the following error. The object 'DF__Morningst__LastU__19EB91BA' is dependent on column 'LastUpdated'.
ALTER TABLE DROP COLUMN LastUpdated failed because one or more objects access this column. I tried deleting the concerned constraint. But the next time I get the same error with a different constraint name. I want to find out if I can dynamically check the constraint name and delete it and then drop the column. Can anyone help.IF EXISTS(SELECT 1FROM sysobjects,syscolumnsWHERE sysobjects.id = syscolumns.idAND sysobjects.name = TablenameAND syscolumns.name = column name)BEGIN EXECUTE ('ALTER TABLE tablename DROP CONSTRAINT DF__SecurityM__DsegL__08C105B8')EXECUTE ('ALTER TABLE tablenameDrop column columnname)ENDGO
 

View 1 Replies View Related

Alter A Column To Be The Table Identity Column

Aug 3, 2006

i have a table
table1
column1 int not null
column2 char not nul
column3 char

i want to script a change for table1 to alter column1 to be the table identity column. not primary.

View 5 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

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

ALTER TABLE - ADD Column

Sep 27, 2005

I have the table table_x:
col1 INT PRIMARY KEY
col2 VARCHAR

I want to add col3 between col1 and col2. In MySQL it's done with the following query:
ALTER TABLE table_x ADD col3 VARCHAR( 10 ) NOT NULL AFTER col1 ;

In sql server all i can do is to add the column to the end of table. Is there a way to insert a new column in the middle or to move a column to left/right?

View 5 Replies View Related

Alter Table Column

Feb 20, 2008

I would like to alter a table column from char(10) to char(5). I issue the command as :

Alter table mytable alter column mycolumn char(5)

It returns :

Server: Msg 8152, Level 16, State 2, Line 1
String or binary data would be truncated.


How can I perform this task?
Thanks,
Joe.

View 1 Replies View Related

Alter Table New Column And Update

Nov 17, 2006

Hifor MS SQL 2000/2005I am having a table (an old database, not mine) with char value for the column [localisation]Users[name] [nvarchar] (100) NOT NULL ,[localisation] [nvarchar] (100)NULLNow i have created a table [Localisation]Localisation[id_Localisation] [int] NOT NULL,[localisation] [nvarchar] (100) NOT NULLI am adding a new column to UsersALTER TABLE [Users] ADD [id_Localisation] int NULLand I want to update the Column [Users].[id_Localisation] before to drop the column [Users].[Localisation]something like UPDATE [Users] SET id_Localisation = (SELECT Localisation.id_LocalisationFROM Localisation FULL OUTER JOINUsers ON Localisation.Localisation = Users.Localisation)Users.Localisation can have a NULL value (then no id_localisation return)but it doesnt work because it returns > 1 rowthank youhow can I do it ?

View 10 Replies View Related

Alter Table - Adding A Column?

Jul 9, 2014

I'm trying to add a column trough command "ALTER" and I've tried in many different ways.

Here is the result of statement..

View 1 Replies View Related

Alter Table - Adding New Column

Oct 6, 2014

I am having a problem adding new column to a table via SQLCMD . Here is the code

:r ServerParam.sql
:connect $(sqlServer) -U $(sqlUser) -P $(sqlPass)

DECLARE @cmd varchar(5000)
DECLARE @SServer varchar(1000)
DECLARE @database varchar(1000)
DECLARE @tableName varchar(500)

[Code] ....

When I am running this script, it creates the database and the table but when I am trying to add the last to field vi

ALTER TAABLE ADD

I am getting error
----------------------------------------------------------------------
C:CalJobsSQLCMDSQLScripts>SQLCMD -v subgt=SJI txtFile=LTS_ERROR_10022014.TXT
tblName=LTS_ERROR_10022014 -i CreateErrorTableSQL.sql
Sqlcmd: Successfully connected to server 'VULCAN'.
------------------------------------------------
Start processing Table: CalJobsErrors.dbo.SJI_LTS_ERROR_10022014
------------------------------------------------

[Code] ....

View 2 Replies View Related

Set Default Value To Column In Table Using Alter

Apr 25, 2015

How to set a default value to columns in table ..without dropping it.??

View 3 Replies View Related

ALTER TABLE ADD Column Question

Sep 26, 2006

This has always puzzled me, so I really just wanted to know if it's possible through T-SQL.

TableA has 3 columns:

ColumnA
ColumnB
ColumnD

Is there anyway through T-SQL to add a new ColumnC *between* ColumnB and ColumnD.

ALTER TABLE TableA
ADD ColumnC [varchar](1)

Thanks.

View 3 Replies View Related

Alter Table Drop Column Error

Apr 11, 2001

1. We have user defined type (Sql type = bit ) with rule setting it to 0
2. New column(isVIP) was created using this user defined type
3. sp_unbindrule was used to unbind rule from new column (isVIP)
4. Alter table Client drop Column isVIP !!!! (invalid syntax )

Any ideas ?
Thanks

View 4 Replies View Related

Alter Table Column, Which Is Part Of Foreign Key

Apr 1, 2006

In MS SQL Server, I have the following tables with some data in it.create table table1 (column1 varchar(32),column2 int not null,column10 varchar(255),.....primary key (column1, column2),);create table table2 (column1 varchar(32),column2 int not null,column20 varchar(255) not null,....foreign key (column1, column2) references table1(column1, column2));Now, I need to change the all column types from varchar to nvarchar tosupport internationalized character set.I am able to do so, for columns column10 in table1 and column20 oftable2 without any problems by using command:"alter table table1 alter column column10 nvarchar(255);"But, when I try the similar thing for column1 of table1/table2, amgetting one error message saying like: "ALTER TABLE ALTER COLUMN failedbecause one or more objects access this column". I guess, this iscoming because of foreign key relationship between the tables.NOTE: While defining the table2, for foreign key I have not specifiedanything like "on update cascase" ...etc.How can I resolve this issue? Any suggestions/solutions are reallyhelpful to me. Thanks in advance.

View 2 Replies View Related

Newbie-Alter Table To Change Column Name

Apr 22, 2008



I am modifying a table and some of the columns are changing. The following syntax is resulting in errors. What am I doing wrong?


ALTER TABLE [EDB].[SQL_test]

ALTER COLUMN EDBR_Nb EDBR_Nm varchar(10)

View 1 Replies View Related

Check For Column Existance Before Alter Table Statement

Feb 14, 2000

Hello all,

I am trying to add columns to several tables in a singular database. I want to check to see if the column exists in a given table first before executing the alter table command so that I can skip that command if the column already exists, and avoid aborting my script prematurely. I can't seem to find a way to check for the column's existance. Any suggestions?

View 2 Replies View Related

Transact SQL :: Alter Table To Rename Column Name With No Space

Oct 27, 2015

I want to alter my all tables to change the name of all columns.
 
I need this because all column names were created with space and I want to remove the space for future work .

For example – In Table Customer there is a column name [Cust_Id ] and I want to change it with [Cust_Id]

View 11 Replies View Related

Alter Table Add Column - How Do You Add A Column After Say The Second Column

Jul 11, 2007



When you use "Alter Table add Column", it adds the column to the end of the list of fields.



How do you insert the new column to position number 2 for instance given that you may have more than 2 columns?



Create table T1 ( a varchar(20), b varchar(20), c varchar(20))



Alter table add column x varchar(20)

so that the resulting table is

T1 a varchar(20), x varchar(20), b varchar(20), c varchar(20)



Can this be done programmatically?













View 33 Replies View Related

SQL Server 2008 :: Alter Column And Reindex 100M Row Table?

Jun 3, 2015

I inherited a system which has an index on a set of columns which allow more than 900 bytes of data in it. We know one of the fields can be shortened to shrink the potential key size below 900 bytes.

The problem is the table is about 120m rows, and the index currently on that column is seeked (sought?) on about 2.5m times a day.

At its simplest, I want to drop the existing index, alter the column to shrink the varchar size, and then rebuild the index on the newly shortened column.

On a smaller, less used table, I might just do this in outside of business hours and call it a day, but I'm concerned that this will take a long time and block a lot of operations.

1) IIRC, shrinking a column, unlike widening it, is much more expensive, even if there are no values which would actually end up trunacted. Is this right?

2) I did a few tests on some other smaller (2+ m) row tables and was still able to select data out of the table. I don't think this covered all the read scenarios, but are there known scenarios which would simply not work during an index build?

3) I haven't yet tried DML operations to the table while it's doing either the column update or an index build. what scenarios would or would not be blocked?

View 0 Replies View Related

Add Calculated Field In Order Table Based On Price Column In Product Table

Nov 18, 2014

I have 2 tables: Order(ID, Quantity) and Product(ID,Name, Price) and I want to add a calculated field in Order table based on the price column in the Product table. How do i do that?

this query returns the values i want in the table.

select a.quantity * b.price
from tblCustomerPurchases as a
join tblProduct as b
on a.ID=b.ID

View 17 Replies View Related

Altered Table-changed Column From Text To Varchar And Now Having Issues With Alter Switch

Feb 14, 2008

Working on partitioning a few large tables. One of the tables included a text column and the €œTEXTIMAGE_ON [PRIMARY]€? clause which would prevent the partitioning of this table. After some research we found that the data was legacy and no longer used. We updated the column on the affected rows to NULLS and altered the column to a VARCHAR(20)
When I attempted to run the ALTER TABLE SWITCH I encountered the error
Msg 4947, Level 16, State 1, Line 1
ALTER TABLE SWITCH statement failed. There is no identical index in source table 'LocalDeltanet.dbo.testresultsjoe' for the index 'PKIDX_testSummary' in target table 'LocalDeltanet.dbo.testresults_part'.
After a lot of grief and testing I determined that the message was bogus and the real issue is that the 'sys.tables' still has €œlob_data_space_id€? with a value of 1 for this table.
I created a copy of the table with the text column altered to varchar and one with just the varchar to begin with. After copying data from the original table, I tried to run the alter switch. It failed once again for the text column altered to varchar table, but it worked for the varchar from the start.

Since it appears that this value is causing my issues, is there anyway to update the table in place. I know I can BCP the data out, but that would take too long and would defeat the advantage of using the alter switch method.

BOL States:

The allow updates option is still present in the sp_configure stored procedure, although its functionality is unavailable in Microsoft SQL Server 2005 (the setting has no effect). In SQL Server 2005, direct updates to the system tables are not supported. This means we cannot update the table manually.

Thanks

View 1 Replies View Related

How To Re-order The ID Column Of A Table?

Oct 5, 2007

I have a table that I want to re-order the ID column. The ID are not in order now due to some insertion and deletion. What are the steps to re-order the ID column?

Thanks in advance.

View 6 Replies View Related

Changing Column Order In A Table

Jul 20, 2005

This subject has been posted several times, but I haven't seen a goodanswer.Problem:I want to change the order of the columns in a table using T-SQL only.Explanation:After running your code, I want to see the following table...CREATE TABLE [dbo].[TableName] ([First_Column] [int] NULL ,[Second_Column] [varchar] (20) NULL) ON [PRIMARY]look like this...CREATE TABLE [dbo].[TableName] ([Second_Column] [varchar] (20) NULL ,[First_Column] [int] NULL) ON [PRIMARY]Limitations:Don't post if your post would fall in the following categories:1. If you don't think it can be done2. If you think Enterprise Manager is the only way to do this3. If you think I should just change the order of my Selectstatements4. If you want to state that order column doesn't matter in arelational database5. If you want to ask me why I want to do thisWish:Hopefully the answer WON'T involve creating a brand new table, movingthe data from old to new, dropping the old table, then renaming thenew table to the old name. Yes, I can do that. The table I'm workingwith is extremely huge -- I don't want to do the data juggling.Thanks in advance!

View 2 Replies View Related

Transact SQL :: Order By A Column From Another Table

Sep 2, 2015

I have two tables, one is called (questions), the second one (answers).

questions columns are (ID,questionTitle)

answers columns are (ID,questionID,answer, answerDate)

I use this query to load data: "SELECT q.questionTitle,COUNT (a.ID),a.answerDate FROM questions q LEFT JOIN answers a ON q.ID=a.questionID" the query is easy, but my problem which I can't solve is how can I fetch the data ordered by the column answerDate, I mean I want the first record to be the one which has the most recent answer and so on.

View 12 Replies View Related

Does Column Order Matter When Creating A Table?

Mar 16, 2001

Does column order matter when creating a table? For example, Should NOT NULL columns always come before NULL columns? Should most frequently used columns always be near the top? What about text, ntext and image data types? Should they always appear near the end of the column order?

View 1 Replies View Related

Mass Table Structure Change For Column Order

Feb 26, 2008



Say you have an existing populated SQL 2005 database, with 700+ tables, and you want to just change the order of the columns inside every table. Short of manually building conversion scripts, anyone know an automated way to do this? I was thinking thru ways to do them all in one shot, and have tools like Erwin and DbGhost that could be used also. Basically moving some standard audit columns from the end of the tables to just after the PK columns.

Thanks, Bruce

View 8 Replies View Related

How To Select Data From Excel Table By Original Column Order?

Feb 21, 2007

Hello, everyone:

I have an Excel table that has columns like,

Vendoe_Name
Level
Address
Email
Phone

I use the statemen

SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',
'Data Source=C: est.xls;Extended Properties=Excel 8.0')...[Sheet1$]

and got output by column order,

Address
Email
Level
Phone
Vendoe_Name

How to make output by original column order like,

Vendoe_Name
Level
Address
Email
Phone

Any help will appreciated. Thanks

ZYT

View 1 Replies View Related

Adding An Auto-increment Column To Existing Table With A Particular Order

Oct 19, 2005

Hello all,I'm using SS2K on W2k.I'v got a table say, humm, "Orders" with two fields in the PK:OrderDate and CustomerID. I would like to add an "ID" column whichwould be auto-increment (and would be the new PK). But, I would reallylike to have orders with the oldest OrderDate having the smallest IDnumber and, for a same OrderDate, I'd to have the smallest CustomerIDfirst. So my question is:How could I add an auto-increment column to a table and make it createits values in a particular order (sort by OrderDate then CustomerIDhere)?In the real situation, the table I want to modify has around 500krecords and the PK has 5 fields and I want to sort on three of them.Thanks for you helpYannick

View 7 Replies View Related

Column Order/presentation In Virtual Table (result Set From Viewor UDF)

Sep 1, 2006

I was just messing around with some ad hoc views and table returningUDFs today so I could look at and print out data from a small tableand noticed something strange.If I stick my select statement into a View the columns are returned inthe order I specify in the SELECT, but if the same statement is in a UDF(so I can specify a parameter), the columns are not returned in theorder specified in statement.I know that relations don't have a specified column order, but it was myunderstanding that a SELECT statement could be used to define how youwant your data presented. Views seem to respect the order specified inthe SELECT, but functions don't.What am I missing? Is there some way to force the order of the columnsreturned from a SELECT?View:CREATE VIEW dbo.View1ASSELECT Ident, Text, Type, ParentStmt, ForStmt, IfStmt, ChildStmt,ThenStmt, ElseStmt, NextStmtFROM dbo.tblStmtWHERE (Ident LIKE '4.2.%')Column order from this view:Ident, Text, Type, ParentStmt, ForStmt, IfStmt, ChildStmt, ThenStmt,ElseStmt, NextStmtFunction:ALTER FUNCTION dbo.Function1(@SearchPrm varchar(255))RETURNS TABLEASRETURN ( SELECT Ident, Text, Type, ParentStmt, ForStmt, IfStmt,ChildStmt, ThenStmt, ElseStmt, NextStmtFROM dbo.tblStmtWHERE (Ident LIKE @SearchPrm) )Column order from this function:Type, Text, ElseStmt, NextStmt, IfStmt, ChildStmt, ThenStmt, Ident,ParentStmt, ForStmtTable:(I know that this table isn't entirely normalized, but it serves mypurposes to have a matrix instead of a fully normalized relation):CREATE TABLE dbo.tblStmt (StmtID INT IDENTITY(1,1) CONSTRAINT PK_Stmt PRIMARY KEY,Ident VARCHAR(255),Text TEXT,ErrorText TEXT,Type INT,ParentStmt VARCHAR(255),ChildStmt VARCHAR(255),IfStmt VARCHAR(255),ForStmt VARCHAR(255),ThenStmt VARCHAR(255),ElseStmt VARCHAR(255),NextStmt VARCHAR(255),FullName VARCHAR(255),LocalName VARCHAR(255),Method INT)INSERT INTO tblStmt Ident, Text, Type, ParentStmt, NextStmtVALUES('4.2.1', 'LineNumberOfResp := EMPTY' 64, '4.2', '4.2.2')INSERT INTO tblStmt Ident, Text, Type, ParentStmt, ChildStmt, ForStmt,NextStmtVALUES('4.2.2', 'FOR K:= 1 TO 2', 128, '4.2', '4.2.3','4.2.7')INSERT INTO tblStmt Ident, Text, Type ParentStmt, ChildStmt, ForStmt,NextStmtVALUES('4.2.3', 'Person[K].KEEP', 16, '4.2', '4.2.3.1', '4.2.2', '4.2.4')INSERT INTO tblStmt Ident, Text, Type, ParentStmt, NextStmtVALUES('4.2.3.1' 'AuxInterviewerName := DOSENV', 64, '4.2.3', '4.2.3.2')

View 3 Replies View Related







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