Add SQL Count Column To Existing Table

Apr 22, 2008

I have a table for blog comments I want to add a column that counts the number of comments for each article.

existing table looks like this:

CommentID

ArticleID (FK)

commentAuthor

authorEmail

comment

commentDate (getDate())


I would like to add a column that counts the number of total comments for each article.This will give me what I want using the VS query tool:

"SELECT COUNT(comment) AS Expr1 FROM UserComments WHERE (articleid = @articleid)"

But can I add that to the table somehow so it does it automagically???

View 5 Replies


ADVERTISEMENT

Insert COUNT Into An Existing Table

Jan 31, 2008

I need to run a query and insert the count results and a name of another table into an existing table.

I have 20 jobs that import records from text files into seperate tables. When that completes I want the count to be sent to another table along with the table name that the count was run on. Any ideas? I can't get SELECT INSERT to work.

Matt

View 1 Replies View Related

Adding Column To A Table Before An Existing Column

Mar 30, 2004

I simply need the ability using SQL to add columns in an existing table before (or after) columns that already exist.

The MS SQL implementation of ALTER TABLE doesn't seem to provide the before or after placement criteria I require. How is this done in MS SQL using SQL or is there a stored procedure I can use?

Thanks.

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 Can I Add A Column To An Existing Table

Nov 14, 2007

Hi everyone!

I just started with SQL and SQL Server 2005. I cantfind in my books how to add a column to an existing table. It should be a primary key, auto_increment column.

Hope someone can help, many thanks in advance

Greetings from Vienna Austria

landau

View 2 Replies View Related

Inserting A Column In An Existing Table

Mar 5, 2004

I have an existing table (see below).

-----------
[FormCode] [varchar] (4) NULL ,
[FiscalYear] [char] (4) NULL
-----------

I want to add the column below after the [FormCode] when my SPROC runs.
-----------
[FiscalMonth] [char] (2) NULL
-----------

Any ideas would be a big help?
TIF

View 7 Replies View Related

Adding And Populating A Column To Existing Table

Dec 5, 2005

Sorry I'm pretty new to SQL so I don't know if this is a simple question. I have a table, and I am trying to add a column to the table and populate this column using what would be called an 'IF' function in Excel.

Basically 'column A' has numbers in it. I want SQL to look at 'column A' and if the first 5 digits of the number in 'column A' are 00001, then put 'description A' into new column 'column B'. If the first 5 digits of the number in 'column A' are 00002, then put 'description B' into 'column A' etc.

Any ideas?

View 2 Replies View Related

Adding Column With Primary Key In Existing Table

Jan 21, 2014

I want to add new primary key into existing table which already has a primary key. But,I do not want to remove the old primary key, since there are many records and the old primary key also have relationship with other table

When I am using this query:

alter table hem154
add indexNO uniqueidentifier default newid()

alter table hem154
add CONSTRAINT pk_hem154_indexNo PRIMARY KEY (PK_indexNO)
go

Note:
Hem154 ~ Table name
indexNo ~ Column Name

I get this runtime error:

Msg 1779, Level 16, State 0, Line 1
Table 'hem154' already has a primary key defined on it.
Msg 1750, Level 16, State 0, Line 1

Could not create constraint. See previous errors.

View 4 Replies View Related

Adding An Identity Column To Existing Table

Sep 11, 2006

I removed all constraints in order to load a bunch of data into a table, now I'm wondering if I can add an identity column to this table which does contain data or if I have to create a new table with the identity column and insert the data into that.

thx

Kat

View 8 Replies View Related

Adding A Indentity Column In An Existing Table.

Feb 20, 2008



Dear Friends,

I need a SQL Query to add a identity coloumn for anExisting table. (ie) when i try to alter the table i want to add an identity coloumn.

Thanks in advance.

View 8 Replies View Related

Replication :: Add A Not Null Column To Existing Table

Aug 27, 2015

We have a requirement to add a not null column to an existing table.

I created the column with null and updated with single quotes, and then converted the column into not null.

Now, I can see in the publisher, it went fine. but in the subscribers, i'm getting the error as, can not insert null value. I then tried to make column as null to resolve the issue, but still it is holding the same error and not proceeding further.

Now I even dropped the column. still same issue. how can I resolve this issue? I'm using sql server 2008 R2 with SP3. replication type is Merge replication.

View 2 Replies View Related

How Can Update Specific Column In Existing Table

Feb 4, 2006

I am building a data warehouse. I have many columns I want to populate in a fact table using integration services. Sample fields are: companyID, companyName, companyNumberOfAccounts, company, NumberOfUsers.

In the integration services package, I would like to keep this fact table in place and populated with data and to build integration services packages that update each of the existing row's specific columns (e.g. companyNameOfAccounts) one by one. For example, I have a source of data that has companyID and companyNumberOfAccounts data.

Is it possible to use the SQL Server Destination or OLE DB Destination Integration Services elements to import companyID and companyNumberOfAccounts data so that existing records just have their companyNumberOfAccounts column updated?

View 1 Replies View Related

Not Able To Create An Identity Column For An Existing Database Table

Feb 1, 2008

I am working with a table in SQL server. I have a column that I want to designateas an identity column. I am not able to do this, because the field for "Identity Specification" is not editiable.
What I did was I went to sql server, right clicked and selected "Modify".The column properties dialog box/edit grid is then displayed with attributesthat I can modify.
There are two major nodes in this dialog box. One is named "General" and the otheris named "Table Designer". I expand the "Table Designer" node and then go to the node labeled "Identity Specification" It is here where I would like to edit thevalues.
The values that are listed for edit are listed below. BUT, the problem is thatI can place my cursor in those fields, but I am not able to change/edit them.Can anyone tell me what the problem is here? and how I can fix it?
 +Identity Specification   (Is Identity)   Identity Increment   Identity Seed

View 3 Replies View Related

WARNING When Adding A Column On SQL Server Existing Table

Feb 28, 2007

After i run the sql which adds some columns on one particular table.I am getting this Warning

Warning: The table 'usac499_499A' has been created but its maximum row size (9033) exceeds the maximum number of bytes per row (8060). INSERT or UPDATE of a row in this table will fail if the resulting row length exceeds 8060 bytes.

I got a series of the above warning message , but the coulmn wa created.

View 10 Replies View Related

Dropping The Null Characteristic On An Existing Table Column

Jun 11, 1999

I am trying to drop the "allow nulls" characteristics on an existing table
column. I know that there are not Nulls currently in this column, nor will
there ever be. How do I get rid of that "allow nulls" checkmark on an
existing table structure? Thanks, Craig.

View 1 Replies View Related

SQL Server 2012 :: How To Add A Primary Key For Existing Column In The Table

Oct 19, 2015

How to add a primary key for existing column in the table

View 8 Replies View Related

DB Design :: Add A New Int Identity Column As Primary Key To Already Existing Table

Sep 3, 2015

We want to add a new int identity column as a primary key to an already existing table that has a primary key on Guid. Here is the DDL:

CREATE TABLE [dbo].[VRes](
[VResID] [uniqueidentifier] NOT NULL,
[Mes] [varchar](max) NOT NULL,
[PID] [uniqueidentifier] NOT NULL,
[Segt] [int] NOT NULL,

[code]....

Also we currently have 3 million rows on this table. Is having an integer column as identity column and primary key better or shd I consider using BigInt?

View 4 Replies View Related

Reporting Services :: How To Add Identity Column Into Existing Table

Jun 10, 2015

how to add identity column into existing table in sql.

View 5 Replies View Related

Add Column To Existing Table With Large Number Of Rows

Dec 24, 2007

Hey Guys

i need to add a datetime column to an exisitng table that has like 1.2 million records and its being accessed frequently
but i cant afford to stop the db at all

whenever i do : alter table mytable add Updated_date datetime

it just takes too long and i have to stop executing the query after a couple of mins
I am running sql express 2005 sp2. db size is over 3 gb but still under the 4 gb limit

can u plz advice on how to add this column. its urgent!!

thanks in advance

View 5 Replies View Related

SQL Server 2012 :: New Column In Existing Table And Uploading Data

Jan 13, 2015

Need to change the datatype of existing column which has huge data.

I'm performing below steps

1. Create new column with correct datatype in the same table
2. copy data into new column
3. drop indexes on column
4. <<<>>>
now the existing column also has many SP dependent and I do not wish to drop them.
5. rename existing column to xxx
6. rename new column to correct column
7. drop old column
8. make required indexes

View 9 Replies View Related

SQL Server 2008 :: Adding Column To Existing Replicated Table

Feb 9, 2015

I have a scenario where I need to add a blank column to a table that is a publisher. This table contains over 100 million records. What is the best way to add the column? In the past where I had to make an update, it breaks replication because the update would take forever as jobs are continuously updating the table so replication can't catch up.

If I alter a table and add a column, would this column automatically get picked up in replication?

View 0 Replies View Related

SQL 2012 :: Partition Existing Table On Foreign Key (datetime) Column?

May 28, 2015

Is it possible to partition an existing table on a foreign key (datetime) column? Also would partition switching work?

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

Damn! SQLServer2000 Can't Add A NOT NULL COLUMN Even In One Empty Existing Table!

Jan 8, 2007

Damn! SQLServer2000 can't add a NOT NULL COLUMN even in one emptyexisting table!That is, A is the existing table and it is emtpy, I want to add one NOTNULL COLUMN (col_new) to A using following T-SQL statement, then itwill fail.ALTER TABLE A ADDcol_new varchar(600) NOT NULLGOYou should change it to these statements in SQLServer2000:ALTER TABLE A ADDcol_new varchar(600) NULLALTER TABLE A ALTER COLUMN col_new varchar(600) NOT NULLGOah, ridiculous! right?Fortunately, this stupid behavior is changed in SQLServer2005. Thefirst T-SQL statements works.

View 1 Replies View Related

Transact SQL :: Unable To Change Column Order Of Existing Table In Server

Jul 23, 2015

In y sql server table has millions of records available. I don't want to drop the tables.

My requirement is I want to change the column order of an existing table. some tables I am able to saving on design window Like Below image.

Even I had generate a script and using that script trying to execute on Management Studio but unable to saving the new column orders. I am getting the Timeout expired error after couple of minutes. How can we save the orders without dropping the table !

View 13 Replies View Related

Count Changes On One Column In A Table

Oct 26, 2007

I've a nub question that someone probably has the fast answere too.

How do I count the number a columnvalue in a table has changed? I was starting to write a stupied cursor but there has to be a much smarter way.

I've a case where I need to count the number of times the salary in a table for individual employees changes.

Thanks in advance!

View 2 Replies View Related

How To Count Particular Text (/) From A Column In A Table?

Jun 16, 2008

I m using SQL Server 2000.
I have Tabel named Topic and have a column name lineage.  lineage has data like following:
//////546707//546707//546707/43213/
Now I want to get records who has only one "/" in it's crreponding lineage column.
 Can somone tell me how to do that in SQL Server 2000?
Thanks
Khushbu

View 2 Replies View Related

Updating A Column With A Count From Another Table?

May 18, 2014

My goal is to with one update statement, fill TABLE1.counter (currently empty) with the total count of TABLE2.e# (employee). Also, if TABLE1.e# isn't in TABLE2.e# then it sets it to "0" (TABLE1.e# 8 and 9 should have a counter of 0) This is for sqlplus.

e.g. TABLE2:

e#
--
1
2
3
4
5
5
6
7
7
1
2
3
4
5
UPDATE TABLE1
SET counter = (
SELECT COUNT(TABLE2.e#)
FROM TABLE2 INNER JOIN TABLE1 ON (TABLE2.e# = TABLE1.e#)
GROUP BY TABLE2.e#);

--^Doesn't work

so my TABLE1 should be:

e# counter
-----------
1 .. 2
2 .. 2
3 .. 2
4 .. 2
5 .. 3
6 .. 1
7 .. 2
8 .. 0
9 .. 0

(The .. is just spacing to show the table here)

View 1 Replies View Related

How To Get Maximum Count Of A Column In A Table.

Dec 6, 2007

i have a table with productID and OrderID. For ech product there are orders.
So for each productID there are lot Of OrderID's are present.
My data like

ProductID OrderID

1 12012
1 12447
1 12478
2 24154
2 21457 etc.......

so, i need to get the maximum count for a product.

i can do by using Temporary tables. but i need without using temporary tables.

please help me out.

thanks
-Praveen.

View 12 Replies View Related

Verifying A Table's Column Count Across Servers?

Jan 31, 2005

Hi folks!

The boss has decided that the data from a table we have on one database (containing daily data) needs to be copied to a "history" table on a different database, on a different server.

The transfer will probably be done with a scheduled stored procedure, and all columns will be transferred EXCEPT for two columns in the source table, which are not present in the destination table. This means instead of an "INSERT Dest SELECT * FROM Source" I have to do an "INSERT Dest SELECT yada,yada,yada... FROM Source" in order to disregard the columns we don't care about. NO problem.

I was thinking (you should smell trouble - and sawdust burning at this point) that this leaves us open to a punch below the belt later when a new column is added to the Source table, since we are using a definitive list of columns to move rather than a *, and the new column could be added without the otherwise system-generated, *-sponsored "gentle reminder" that it also needs to be added to the Dest table. I'm not as convinced as The Boss that "Oh, I'm sure we'll remember to add it to the history table when that happens" :lol:

So, long story shorter (nah...too late for that) - I figure I can write a check at each day's historical transfer on the count of columns in one table verses the other, and send an email or fail the job if the count doesn't make sense.

For example, if the Source table has 34 columns, since we don't care about two of them, the Dest table should have 32 columns, if things are still in synch. OK, I think (insert burning sawdust smell here), I can use a SysObjects thang to count rows. BOL points out INFORMATION_SCHEMA.COLUMNS as a possibility.

Here is the code I think (sawdust) can be used:select ((select count(*) from SourceDb.INFORMATION_SCHEMA.columns
where table_name = 'Source') - (select count(*) from HISTSERVER.DestDb.INFORMATION_SCHEMA.columns
where table_name = 'Dest')) as ColumnDiff

Trouble is...this fails because apparently the INFORMATION_SCHEMA thang doesn't do well with remote servers.

Can anyone figure a way around this, or suggest an alternative? I'm still looking, but thought I'd also toss it out onto the board for your generous consideration.

Thanks - and can you BELIEVE the year is already 1/12th of the way OVER?!?!?!
Paul

View 4 Replies View Related

How Count Column In Pivot Table- And Add Result Row

Jan 20, 2008

how count column in pivot table- and add result row
i need to calculate each column
for example
day1 day2 day3 day4 day5
-------------------------------------------------------------------------
1 2 1 2 3
1 2 3 2 2
2 3 2 1 2
2 3 0 0 0
-----------------------------------------------------------new result row
ok ok 1|2|3 1 3

i need to check each column
if i have twice each number
if not show the missing number
TNX




Code Block
DECLARE @Employee TABLE (ID INT, Date SMALLDATETIME, ShiftID TINYINT)
DECLARE @WantedDate SMALLDATETIME, -- Should be a parameter for SP
@BaseDate SMALLDATETIME,
@NumDays TINYINT
SELECT @WantedDate = '20080301', -- User supplied parameter value
@BaseDate = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', @WantedDate), '19000101'),
@NumDays = DATEDIFF(DAY, @BaseDate, DATEADD(MONTH, 1, @BaseDate))

IF @Numdays > 28
BEGIN
SELECT p.ID,
p.[1] , p.[2],p.[3], p.[4], p.[5], p.[6], p.[7], p.[8], p.[9], p.[10], p.[11],
p.[12], p.[13], p.[14], p.[15], p.[16], p.[17], p.[18], p.[19], p.[20], p.[21],
p.[22], p.[23], p.[24], p.[25], p.[26], p.[27], p.[28], p.[29], p.[30], p.[31]
FROM (
SELECT ID,
DATEPART(DAY, Date) AS theDay,
ShiftID
FROM v_Employee
WHERE Date >= @BaseDate
AND Date < DATEADD(MONTH, 1, @BaseDate)
) AS y
PIVOT (
min(y.ShiftID) FOR y.theDay IN ([1], [2], [3], [4], [5], [6], [7],[8] , [9], [10], [11],
[12], [13], [14], [15], [16], [17], [18], [19], [20], [21],
[22], [23], [24], [25], [26], [27], [28], [29], [30], [31])
) AS p
END

View 12 Replies View Related

Trigger To Update Table Based On COUNT Of Column

Sep 26, 2007

Hello again,

I'm hoping someone can help with with a task I've been given. I need to write a trigger which will act effectively as a method of automatically distributing of incoming call ticket records. See DDL below for creation of the Assignment table, which holds information on the call ticket workload.





Code Snippet
CREATE TABLE #Assignment
(CallID INT IDENTITY(1500,1) PRIMARY KEY,
AssignmentGroup VARCHAR(25),
Assignee VARCHAR(25)
)
GO
INSERT #Assignment (AssignmentGroup, Assignee)
VALUES ('Service Desk', 'Jim Smith')
INSERT #Assignment (AssignmentGroup, Assignee)
VALUES ('PC Support', 'Donald Duck')
INSERT #Assignment (AssignmentGroup, Assignee)
VALUES ('Service Desk', 'Joe Bloggs')
INSERT #Assignment (AssignmentGroup, Assignee)
VALUES ('Service Desk', 'Joe Bloggs')
INSERT #Assignment (AssignmentGroup, Assignee)
VALUES ('Service Desk', 'Joe Bloggs')
INSERT #Assignment (AssignmentGroup, Assignee)
VALUES ('PC Support', 'Donald Duck')
INSERT #Assignment (AssignmentGroup, Assignee)
VALUES ('PC Support', 'Mickey Mouse')

GO

SELECT COUNT(CallID) AS [Total Calls], AssignmentGroup, Assignee
FROM #Assignment
GROUP BY AssignmentGroup, Assignee
ORDER BY COUNT(CallID) DESC , AssignmentGroup, Assignee






What I need to do is write a trigger for on INSERT to automatically update the Assignee column with the name of the person who currently has the least active calls. For example, using the data above, the next PC Support call will go to Mickey Mouse, and the next two Service Desk calls will go to Jim Smith.


So, the logic for the trigger would be

UPDATE #Assignment
SET Assignee = (SELECT Assignee FROM #Assignment WHERE COUNT(CallID) = MIN(COUNT(CallID))


But that's only the logic, and obviously it doesn't work with the syntax being nothing like correct.

Does any one have an idea or pointers as to how I should go about this?

Grateful for any advice, thanks
matt

View 5 Replies View Related

Integration Services :: Add New Column Based On Existing Column Using Derived Column Task?

Jul 28, 2015

I have a excel file which has a column called "Code" and their values are A,B,C,D,E,F,G,H.  I want to create a new column called "status" based on the values of "Code".

Code:

A
B
C
D
E
F
G
H

If A,C,E,G then "status" = "Active" else if  B,D,F,H then "Status" = "Inactive". I like to do it using "Derived Column".

View 4 Replies View Related







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