473,761 Members | 8,813 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

About adding a new column...

Suppose I have a table with the following columns: Year, SalesInEurope,
SalesInAmerica, TotalSales. I want to add a new column called
SalesInAsia, say, but I want it to appear before TotalSales. How can
this be achieved?
Thanks,

Bruno

Sep 12 '05 #1
13 6508
Well first of all I would strongly recommend you change the design of
your table. It's a mistake to represent data in column names because it
makes your data much harder to manipulate and maintain. Basic design
sense would indicate is that the "region" is an attribute and
"America", "Asia", etc are values. In other words one would normally
expect to see ONE column for Region and one column for Sales Value.
Presenting different regions as columns is something you should do in a
report, not in a table.

To answer your specific question, there is no single command to add a
column at a particular ordinal position. The only way to do that in a
table is to re-create the table, or maybe in this case to rename the
columns and repopulate the data. In a production application table
column order is mostly unimportant - the order is determined by the
column order in a SELECT statement, not in a table. If you feel you
have a good reason to change the column order in the table on a
non-production system then you could try using the table designer in
Enterprise Manager. EM will allow you to re-order the columns and
re-create the table for you. EM will also generate the script for you
if you want to see how it's done.

Hope this helps.

--
David Portas
SQL Server MVP
--

Sep 12 '05 #2
David Portas (RE************ *************** *@acm.org) writes:
In a production application table column order is mostly unimportant -


Yes, if no humans ever look at the database - which is highly unlikely
if the system is in production.

I just get so tired of this. Everytime someone asks about placing a column
in a certain order in a table, there is always someone knowledgable who
needs to tell that person he does not need to do that.

Column order *does* matter, because it makes it so easy to work with.
The fact that SQL Server does not provide any simple command to change
order is no reason to tell people they want the wrong thing.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Sep 12 '05 #3
I agree with most of what you said. What I mean by "mostly unimportant"
is that for most people most of the time the column order returned by
SELECT * is not important enough to justify the effort and impact of
recreating a table. That's my experience anyway.
The fact that SQL Server does not provide any simple command to change
order is no reason to tell people they want the wrong thing.


I don't agree with this. There is good reason to tell people they are
wrong. Implied column ordering is a serious failing of SQL and has lead
to much bad code and incorrect results. I want to discourage anyone
from building column order dependencies into their systems. I would do
so even if SQL Server made it a trivial task to re-order columns - in
fact I'd be even more vocal about it if there were a trivial solution!
I agree that there is a case for physically ordering columns for
support and development purposes but I don't want people to confuse
that service delivery issue with their business's presentational
requirements.

--
David Portas
SQL Server MVP
--

Sep 13 '05 #4
David Portas (RE************ *************** *@acm.org) writes:
I agree with most of what you said. What I mean by "mostly unimportant"
is that for most people most of the time the column order returned by
SELECT * is not important enough to justify the effort and impact of
recreating a table. That's my experience anyway.
I would agree that with the current state of the art, that rearranging
columns is a bit too much hassle. Then again, if I were to take over
maintenance were column order were accidental, and particularly different
in different in different instances of the same schema, I might consider
it. (After all, I have the tools to do this rather easily. It is just
the time to run it that could be expensive.)
I don't agree with this. There is good reason to tell people they are
wrong. Implied column ordering is a serious failing of SQL and has lead
to much bad code and incorrect results. I want to discourage anyone
from building column order dependencies into their systems. I would do
so even if SQL Server made it a trivial task to re-order columns - in
fact I'd be even more vocal about it if there were a trivial solution!
I agree that there is a case for physically ordering columns for
support and development purposes but I don't want people to confuse
that service delivery issue with their business's presentational
requirements.


One should not forget that there actually users out there whose only
application is Open Table in Enterprise Manager. I don't like it myself,
but there was a huge outcry when Microsoft tried to leave it out from
Management Studio in SQL 2005.

Of course, using SELECT * in combination with references to columns by
number in client code is extremely bad practice.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Sep 13 '05 #5
BD
I am asked to do this on a very regular basis.

The logic I normally go through is as follows:

-delete trigger for the original table (if it exists);
-delete all views for the original table, if they exist (they will keep
referencing the original table even after it is renamed)
-rename the original table to table_name_old (executing the native
sp_rename stored procedure)
-create the new table in the correct structure
-create new default value constraints unless you're okay with system
generated names for default value constraints
-insert into new_table (all columns except for new one) as select (all
columns) from original table
-recreate view(s) if applicable
-recreate trigger if applicable
*then confirm all is well before dropping the old table.

I would recommend making a SQL script for this process, and keeping it
as a template for future use.

I also would recommend SQL scripts over EM or any other GUI: All that
GUIs will ultimately do is provide a nice pretty set of screens and
buttons, and then generate a SQL script which you may or may not see.
Getting used to coding the SQL script will eliminate the middle-man,
and allow you to comfortably replicate the same process again and
again.

I can fire you a sample script with the logic that I use if you like.

Sep 14 '05 #6

"Erland Sommarskog" <es****@sommars kog.se> wrote in message
news:Xn******** ************@12 7.0.0.1...
David Portas (RE************ *************** *@acm.org) writes:
In a production application table column order is mostly unimportant -
Yes, if no humans ever look at the database - which is highly unlikely
if the system is in production.

I just get so tired of this. Everytime someone asks about placing a column
in a certain order in a table, there is always someone knowledgable who
needs to tell that person he does not need to do that.

Column order *does* matter, because it makes it so easy to work with.
The fact that SQL Server does not provide any simple command to change
order is no reason to tell people they want the wrong thing.


I can see your point of view (and often wish in EM I could see columns in
the order I want) but to a point have to disagree with it.

Let me pull a Celko here, but I think getting into the mindshift of thinking
of a table and realizing that order of columns should not be a physical
attribute of the table.

The minute folks assume they are, they start accepting code like select *
from bar and assuming that * will return columns in a specific manner. This
burned us on a code change a year or so ago where due to the way the schema
was changing (partly due to replication) the order of the columns DID in
fact change and of course the programmers who wrote the code in the height
of the dotcom era saved 30 seconds (or about 2 days "internet time" :-) by
typing * instead of a proper column list.

This was fine for 3-4 years until suddenly production code on a high volume
website broke.

Ideally Enterprise Manager could access some sort of metadata that would
store the desired view of columns, independent of the physical layout of the
table.


--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Sep 14 '05 #7
BD (bo*********@ho tmail.com) writes:
I also would recommend SQL scripts over EM or any other GUI: All that
GUIs will ultimately do is provide a nice pretty set of screens and
buttons, and then generate a SQL script which you may or may not see.
Getting used to coding the SQL script will eliminate the middle-man,
and allow you to comfortably replicate the same process again and
again.


You can use EM to get a script, that you can work from. But beware
that the script that EM generates has several flaws, that you need to
fix:

o Remove all BEGIN TRANSACTION and COMMIT TRANSACTION, except the first
BEGIN and the last COMMIT.

o Remove all GO. Instead wrap all the ALTER and CREATE TABLE statements
in EXEC.

o Add SET XACT_ABORT ON first in the script.

o Replace all WITH NOCHECK in the script WITH CHECK.

o Review the script carefully, so that it does not include changes to
do not intend to make. Yes, EM, may add such changes.

The first three points has to do with the transaction scope. You may
not always want a transaction, if you have large tables. But in such
case, you must be prepared to restore a backup if the script fails.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Sep 14 '05 #8
Greg D. Moore (Strider) (mo************ ****@greenms.co m) writes:
I can see your point of view (and often wish in EM I could see columns in
the order I want) but to a point have to disagree with it.

Let me pull a Celko here, but I think getting into the mindshift of
thinking of a table and realizing that order of columns should not be a
physical attribute of the table.

The minute folks assume they are, they start accepting code like select
* from bar and assuming that * will return columns in a specific manner.
This burned us on a code change a year or so ago where due to the way
the schema was changing (partly due to replication) the order of the
columns DID in fact change and of course the programmers who wrote the
code in the height of the dotcom era saved 30 seconds (or about 2 days
"internet time" :-) by typing * instead of a proper column list.

This was fine for 3-4 years until suddenly production code on a high
volume website broke.


Yes, SELECT * does not belong in application code. (Unless it's some
simple throw-away thing like keep track of the local sports club.)

Just like, it is not good practice to call a routine (be that a C++
function of stored procedure) with 20 parameters with positional actual
parameters. Yet, few would argue that it's a good idea to have the
parameters in random order.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Sep 14 '05 #9
On 13 Sep 2005 17:06:25 -0700, BD wrote:
I am asked to do this on a very regular basis.

The logic I normally go through is as follows: (snip)I would recommend making a SQL script for this process, and keeping it
as a template for future use.


Hi BD,

If you make a generic template, then you might wish to include dropping
and recreation of foreign key constraints that reference the table to be
changed. You omitted that from your shortlist.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Sep 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
19313
by: Garry | last post by:
Hi, I am new to python, hope someone can help me here: I have a MS Access exported .txt file which is tab delimited in total 20 columns, now I need to add another column of zero at the 4th column position and a column of zero at the 9th column position. What is the best way to do this? Can I write a while loop to count the number of tab I hit until the counter is 4 and then add a zero in between and thru the whole file? Thanks, Garry
10
4014
by: Eric Petruzzelli | last post by:
If I fill my dataset and there is no data. The dataset is still created with zero rows (all columns are there). When I add my first row using the script below, it takes over 2 seconds to add??? If I add the second row, instant. How can I eliminate this delay?
2
1988
by: Chris Cobb | last post by:
I have a table that currently contains 718000 rows. I wish to add a column to the table. Adding this column anywhere other than the end of the table requires exporting data, a drop and recreate, then a re-import of data. Is there any disadvantage to adding this column to the end of the table. Will this fragment the table. Is a reorg needed? Thanks, - CBC
2
3639
by: Clayton Hamilton | last post by:
I have a DataGrid on a webform bound to a Datasource and can successfully use <ItemTemplate> to create edit/update/cancel functionality for user maintenance of data. I use separate logic to delete a row. Everything works just fine. BUT I would like to add a button to (for example) the DataGrid header, which when pressed will add a new row to the datagrid. This should then allow the user to enter information into text boxes (in some...
3
1955
by: Robin Thomas | last post by:
I am fairly new to ASP.NET so I think I am missing something fundamental. Anyway, quite often I am pulling data from a database, but then I need to use that data to produce more data. A simple example would be: Let's say Column1=StartDate and Column2=EndDate. In addition to displaying Column1 and Column2, I need to do some calculations and display in as Column3. The calculations are easy and can be done in the code-behind. How to display...
2
4758
by: Jef Driesen | last post by:
I'm working on a project where i need to exchange multidimensional data between C/C++ (row-major) and matlab (column-major). I understand the difference between those two mappings to linear memory. Suppose I need an S1 x S2 x ... x Sn dimensional array A. I can have the same layout in memory by reversing the dimensions: A... == A(Sn,...,S1) where I used the C/C++ notation for row-major and the matlab notation
2
1526
by: BerkshireGuy | last post by:
I have a column chart with two series: 1) Number Of Applications 2) Number of Completed Applications. These are in a column format, so it looks like one bar, but colors outline the two numbers. Now I want to have a percentage (Completed Apps/Number Of Apps) over the related column.
1
3552
by: Kimmo Laine | last post by:
Hi! I need to resize the last column in my listview control so that there won´t be horizontal scrollbar. Lets first create lv and add some items: listView1.View = View.Details;
11
3162
by: dennis.sprengers | last post by:
Consider the following multi-dimensional array: --------------------------- $arr = array( array(3, 5, 7, 9), array(2, 4, 6, 8), array(1, 3, 5, 7) ); function add_arrays($arr) { for ($row = 0; $row < count($arr); $row++) {
0
9376
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10136
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9988
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9811
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8813
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7358
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6640
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.