How To Alter A Table In A Trigger?
Oct 29, 2006
Hi,everyone.
I have a problem with SQL SERVER 2005, described as follows,
(1) To create two tables MASTERINFO and PRODUCT,
----TABLE MASTERINFO-----
CREATE TABLE MASTERINFO
(
ID CHAR(2),
FIELDNAME VARCHAR(50),
FIELDTYPE VARCHAR(50),
);
Table MASTERINFO with following records,
MASTERINFO('1','PRODUCTNAME','VARCHAR(50)');
MASTERINFO('2','PRODUCTADD','VARCHAR(50)');
MASTERINFO('3','PRODUCTEXP','VARCHAR(50)');
------TABLE PRODUCT-----
CREATE TABLE PRODUCT
(
ID CHAR(5),
PRODUCTNAME VARCHAR(50),
PRODUCTADD VARCHAR(50),
PRODUCTEXP VARCHAR(50),
);
In our project, field name and field data type of fields PRODUCTNAME,PRODUCTADD and PRODUCTEXP in the table PRODUCT are changed with values of fields FIELDNAME and FIELDTYPE in the table MASTERINFO.That is to say, when using the following UPDATE statement,
UPDATE MASTERINFO SET FIELDNAME='PRODUCTNAME1',FIELDTYPE='VARCHAR(60)' WHEN ID='1';
We hope that field name of field PRODUCTNAME is automatically changed into PRODUCTNAME1 and data type of its is changed into 'VARCHAR(60) in the table PRODUCT.
I want to use a trigger to realize, but I failed for ALTER TABLE statement can not be included in the trigger. How can I do?
Please give me some advice. Thank you in advance.
View 7 Replies
ADVERTISEMENT
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
May 17, 2007
Hi
I'm trying to write a trigger to insert data into an archive file. I added a new trigger using database explorer, wrote the trigger and then saved it. The trigger has an error in it and I need to alter it. Can you tell me how to access the trigger ?
Many thanks
Chris
View 5 Replies
View Related
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
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
Feb 26, 2008
Recently I created a DDL Server-scope trigger using the following:
create trigger stop_alter_database on all server
for ALTER_DATABASE
as
rollback;
print 'database change stopped by stop_alter_database';
go
Then I ran the following script:
alter database [test] modify file (name=test', maxsize=2028mb);
The result was:
Msg 3609, Level 16, State 2, Line 1
The transaction ended in the trigger. The batch has been aborted.
database change stopped by stop_alter_database
The problem is that when I checked the max size of the data file it had changed. So, the statement was never rolled back. Is there something I'm missing because I can't find any documentation or articles that state the inability to rollback alter database statements. Whats going on?
View 2 Replies
View Related
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
Jan 23, 2008
Hi,
I have a trigger set on TABLE1 so that any update to this column should set off trigger to write to the AUDIT log table, it works fine otherwise but not the very first time when table1 has null in the column. if i comment out
and i.req_fname <> d.req_fname from the where clause then it works fine the first time too. Seems like null value of the column is messing things up
Any thoughts?
Here is my t-sql
Insert into dbo.AUDIT (audit_req, audit_new_value, audit_field, audit_user)
select i.req_guid, i.req_fname, 'req_fname', IsNull(i.req_last_update_user,@default_user) as username from inserted i, deleted d
where i.req_guid = d.req_guid
and i.req_fname <> d.req_fname
Thanks,
leo
View 7 Replies
View Related
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
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
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
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
May 26, 2015
which ALTER TABLE/ALTER COLUMN- Statement has a Recreate Table as result ?
View 2 Replies
View Related
Nov 14, 2006
Hey,
I'm new to this whole SQL Server 2005 thing as well as database design and I've read up on various ways I can integrate business constraints into my database. I'm not sure which way applies to me, but I could use a helping hand in the right direction.
A quick explanation of the various tables I'm dealing with:
WBS - the Work Breakdown Structure, for example: A - Widget 1, AA - Widget 1 Subsystem 1, and etc.
Impacts - the Risk or Opportunity impacts for the weights of a part/assembly. (See Assemblies have Impacts below)
Allocations - the review of the product in question, say Widget 1, in terms of various weight totals, including all parts. Example - September allocation, Initial Demo allocation, etc. Mostly used for weight history and trending
Parts - There are hundreds of Parts which will eventually lead to thousands. Each part has a WBS element. [Seems redundant, but parts are managed in-house, and WBS elements are cross-company and issued by the Government]
Parts have Allocations - For weight history and trending (see Allocations). Example, Nut 17 can have a September 1st allocation, a September 5th allocation, etc.
Assemblies - Parts are assemblies by themselves and can belong to multiple assemblies. Now, there can be multiple parts on a product, say, an unmanned ground vehicle (UGV), and so those parts can belong to a higher "assembly" [For example, there can be 3 Nut 17's (lower assembly) on Widget 1 Subsystem 2 (higher assembly) and 4 more on Widget 1 Subsystem 5, etc.]. What I'm concerned about is ensuring that the weight roll-ups are accurate for all of the assemblies.
Assemblies have Impacts - There is a risk and opportunity impact setup modeled into this design to allow for a risk or opportunity to be marked on a per-assembly level. That's all this table represents.
A part is allocated a weight and then assigned to an assembly. The Assemblies table holds this hierarchical information - the lower assembly and the higher one, both of which are Parts entries in the [Parts have Allocations] table.
Therefore, to ensure proper weight roll ups in the [Parts have Allocations] table on a per part-basis, I would like to check for any inserts, updates, deletes on both the [Parts have Allocations] table as well as the [Assemblies] table and then re-calculate the weight roll up for every assembly. Now, I'm not sure if this is a huge performance hog, but I do need to keep all the information as up-to-date and as accurate as possible. As such, I'm not sure which method is even correct, although it seems an AFTER DML trigger is in order (from what I've gathered thus far). Keep in mind, this trigger needs to go through and check every WBS or Part and then go through and check all of it's associated assemblies and then ensure the weights are correct by re-summing the weights listed.
If you need the design or create script (table layout), please let me know.
Thanks.
View 4 Replies
View Related
Jul 20, 2005
Are there any limitations or gotchas to updating the same table whichfired a trigger from within the trigger?Some example code below. Hmmm.... This example seems to be workingfine so it must be something with my specific schema/code. We'reworking on running a SQL trace but if anybody has any input, fireaway.Thanks!create table x(Id int,Account varchar(25),Info int)GOinsert into x values ( 1, 'Smith', 15);insert into x values ( 2, 'SmithX', 25);/* Update trigger tu_x for table x */create trigger tu_xon xfor updateasbegindeclare @TriggerRowCount intset @TriggerRowCount = @@ROWCOUNTif ( @TriggerRowCount = 0 )returnif ( @TriggerRowCount > 1 )beginraiserror( 'tu_x: @@ROWCOUNT[%d] Trigger does not handle @@ROWCOUNT[color=blue]> 1 !', 17, 127, @TriggerRowCount) with seterror, nowait[/color]returnendupdate xsetAccount = left( i.Account, 24) + 'X',Info = i.Infofrom deleted, inserted iwhere x.Account = left( deleted.Account, 24) + 'X'endupdate x set Account = 'Blair', Info = 999 where Account = 'Smith'
View 1 Replies
View Related
Dec 5, 2006
This Audit Trigger is Generic (i.e. non-"Table Specific") attach it to any tabel and it should work. Be sure and create the 'Audit' table first though.
The following code write audit entries to a Table called
'Audit'
with columns
'ActionType' //varchar
'TableName' //varchar
'PK' //varchar
'FieldName' //varchar
'OldValue' //varchar
'NewValue' //varchar
'ChangeDateTime' //datetime
'ChangeBy' //varchar
using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
public partial class Triggers
{
//A Generic Trigger for Insert, Update and Delete Actions on any Table
[Microsoft.SqlServer.Server.SqlTrigger(Name = "AuditTrigger", Event = "FOR INSERT, UPDATE, DELETE")]
public static void AuditTrigger()
{
SqlTriggerContext tcontext = SqlContext.TriggerContext; //Trigger Context
string TName; //Where we store the Altered Table's Name
string User; //Where we will store the Database Username
DataRow iRow; //DataRow to hold the inserted values
DataRow dRow; //DataRow to how the deleted/overwritten values
DataRow aRow; //Audit DataRow to build our Audit entry with
string PKString; //Will temporarily store the Primary Key Column Names and Values here
using (SqlConnection conn = new SqlConnection("context connection=true"))//Our Connection
{
conn.Open();//Open the Connection
//Build the AuditAdapter and Mathcing Table
SqlDataAdapter AuditAdapter = new SqlDataAdapter("SELECT * FROM Audit WHERE 1=0", conn);
DataTable AuditTable = new DataTable();
AuditAdapter.FillSchema(AuditTable, SchemaType.Source);
SqlCommandBuilder AuditCommandBuilder = new SqlCommandBuilder(AuditAdapter);//Populates the Insert command for us
//Get the inserted values
SqlDataAdapter Loader = new SqlDataAdapter("SELECT * from INSERTED", conn);
DataTable inserted = new DataTable();
Loader.Fill(inserted);
//Get the deleted and/or overwritten values
Loader.SelectCommand.CommandText = "SELECT * from DELETED";
DataTable deleted = new DataTable();
Loader.Fill(deleted);
//Retrieve the Name of the Table that currently has a lock from the executing command(i.e. the one that caused this trigger to fire)
SqlCommand cmd = new SqlCommand("SELECT object_name(resource_associated_entity_id) FROM
ys.dm_tran_locks WHERE request_session_id = @@spid and resource_type = 'OBJECT'", conn);
TName = cmd.ExecuteScalar().ToString();
//Retrieve the UserName of the current Database User
SqlCommand curUserCommand = new SqlCommand("SELECT system_user", conn);
User = curUserCommand.ExecuteScalar().ToString();
//Adapted the following command from a T-SQL audit trigger by Nigel Rivett
//http://www.nigelrivett.net/AuditTrailTrigger.html
SqlDataAdapter PKTableAdapter = new SqlDataAdapter(@"SELECT c.COLUMN_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
where pk.TABLE_NAME = '" + TName + @"'
and CONSTRAINT_TYPE = 'PRIMARY KEY'
and c.TABLE_NAME = pk.TABLE_NAME
and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME", conn);
DataTable PKTable = new DataTable();
PKTableAdapter.Fill(PKTable);
switch (tcontext.TriggerAction)//Switch on the Action occuring on the Table
{
case TriggerAction.Update:
iRow = inserted.Rows[0];//Get the inserted values in row form
dRow = deleted.Rows[0];//Get the overwritten values in row form
PKString = PKStringBuilder(PKTable, iRow);//the the Primary Keys and There values as a string
foreach (DataColumn column in inserted.Columns)//Walk through all possible Table Columns
{
if (!iRow[column.Ordinal].Equals(dRow[column.Ordinal]))//If value changed
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "U";//U for Update
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the entry
}
}
break;
case TriggerAction.Insert:
iRow = inserted.Rows[0];
PKString = PKStringBuilder(PKTable, iRow);
foreach (DataColumn column in inserted.Columns)
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "I";//I for Insert
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = null;
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
case TriggerAction.Delete:
dRow = deleted.Rows[0];
PKString = PKStringBuilder(PKTable, dRow);
foreach (DataColumn column in inserted.Columns)
{
//Build and Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "D";//D for Delete
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = null;
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
default:
//Do Nothing
break;
}
AuditAdapter.Update(AuditTable);//Write all Audit Entries back to AuditTable
conn.Close(); //Close the Connection
}
}
//Helper function that takes a Table of the Primary Key Column Names and the modified rows Values
//and builds a string of the form "<PKColumn1Name=Value1>,PKColumn2Name=Value2>,......"
public static string PKStringBuilder(DataTable primaryKeysTable, DataRow valuesDataRow)
{
string temp = String.Empty;
foreach (DataRow kColumn in primaryKeysTable.Rows)//for all Primary Keys of the Table that is being changed
{
temp = String.Concat(temp, String.Concat("<", kColumn[0].ToString(), "=", valuesDataRow[kColumn[0].ToString)].ToString(), ">,"));
}
return temp;
}
}
The trick was getting the Table Name and the Primary Key Columns.
I hope this code is found useful.
Comments and Suggestion will be much appreciated.
View 16 Replies
View Related
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
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
Oct 30, 2007
Table 1
First_Name
Middle_Name
Surname
John
Ian
Lennon
Mike
Buffalo
Tyson
Tom
Finney
Jones
Table 2
ID
F
M
S
DOB
1
Athony
Harold
Wilson
24/4/67
2
Margaret
Betty
Thathcer
1/1/1808
3
John
Ian
Lennon
2/2/1979
4
Mike
Buffalo
Tyson
3/4/04
5
Tom
Finney
Jones
1/1/2000
I want to be able to create a trigger that updates table 2 when a row is inserted into table 1. However I€™m not sure how to increment the ID in table 2 or to update only the row that has been inserted.
View 17 Replies
View Related
Feb 5, 2008
A
ID
Name
1
Joe
2
Fred
3
Ian
4
Bill
B
ID
1
4
I want to be able to create a trigger so that when a row is inserted into table A by a specific user then the ID will appear in table B. Is it possible to find out the login id of the user inserting a row?
I believe the trigger should look something like this:
create trigger test_trigger
on a
for insert
as
insert into b(ID)
select i.id
from inserted i
where
--specific USER
View 9 Replies
View Related
Feb 15, 2006
Is there a way to add a column to an existing table and do it all in C#If my query string is as follows how do I execute the query?ALTER TABLE interests ADD COLUMN Swim VARCHAR(1) NOT NULL DEFAULT('n')ThanksMoonWa
View 2 Replies
View Related
Aug 13, 2002
I think I have blown a gasket..... a elementary simple sp that will not work but I am unable to find an explanation as to why..... please help.
CREATE PROCEDUREbrsp_table_alteration
@var_1 varchar(45)
,@var_2varchar(45)
,@var_3varchar(30)
AS
ALTER TABLE @var_1
ADD@var_2@var_3NULL
Thanks.
View 3 Replies
View Related
Sep 30, 2003
I have a table tblABC which exists in 800 databases. I want to run a cursor to turn off the pk field ID indentity permannetly and then to "insert tblABC select * from tblXYZ".
I have tried the "set indentity_insert tblABC on" statement and failed on insert tblABC select * from tblXYZ.
Is there any alter table related t-sql could permannetly turn off the identity?
thanks
David
View 7 Replies
View Related
Jun 7, 2001
Is there anyway to Insert a new column between two existing columns without creating a new table?
Thanks
View 3 Replies
View Related
Oct 17, 2001
Hi,
is it possible to override the system when adjusting
columns. i.e. a system override setting.
For instance if I've got a column that is indexed and I
want to adjust it from varchar(50) to varchar(51) it lets
me. But if I then try and adjust the column to varchar
(49) I get the error below:
Server: Msg 5074, Level 16, State 8, Line 1
The index 'LastName' is dependent on column 'lastname'.
Server: Msg 4922, Level 16, State 1, Line 1
ALTER TABLE ALTER COLUMN lastname failed because one or
more objects access this column.
I asked this question on another Forum and was told I had to drop the index first. Just thought I'd ask for a second opinion.
Thanks for the help.
Steve
View 1 Replies
View Related
Jan 30, 2004
Hi to all!
I have a silly problem, but I'm not able to solve it!
I know how to add a field in a table via Enterprise manager and I know also via ALTER TABLE command.
...But the problem is: I want to add a field NOT in the last position, but on the middle (for istance)
So, this is possible via Enterprise Manager but with the ALTER TABLE command? How can I add a field without put it in the last position?
...Thanks a lot!
Sergio
p.s.: Sorry for my poor english..I hope you understand my question!
View 2 Replies
View Related
Jun 5, 2008
hello,
i am trying to add a column to every table in a database, if it (doesn't already exist), with the following code:
declare @name varchar(50)
declare c cursor for select name from sys.tables
open c
fetch next from c into @name
while @@FETCH_STATUS = 0
begin
if( (select count(*) from sys.columns
WHERE object_id IN (SELECT object_id FROM sys.tables WHERE name = @name )
and name='ins_id') = 0 )
begin
alter table @name add ins_id int
end
fetch next from c into @name
end
close c
deallocate c
and when i run the script i get the error message
Incorrect syntax near '@name'.
reffering to the alter table statement
So, my question is, how can i actually perform the alter table in this case?
thank you
View 3 Replies
View Related
Mar 2, 2007
Pramod writes "I want to change the primary key field of my database to Identity seed. the table is with data. data should be secured
this is the structure
'=================================
CREATE TABLE [tblStock] (
[StockId] [numeric](18, 0) NOT NULL ,
[ItemID] [numeric](18, 0) NULL ,
[Batch] [varchar] (50) NULL ,
[Qty] [float] NULL ,
[Prate] [float] NULL ,
[SRate] [float] NULL ,
[Mrp] [float] NULL ,
[PTR] [float] NULL ,
[batchid] [numeric](18, 0) NULL ,
[BatchCode] [varchar] (50) NULL ,
CONSTRAINT [PK_tblStock] PRIMARY KEY NONCLUSTERED
(
[StockId]
) ON [PRIMARY] ,
CONSTRAINT [IX_tblStock] UNIQUE NONCLUSTERED
(
[ItemID],
[Batch],
[Prate]
) ON [PRIMARY]
) ON [PRIMARY]
===================================
How do i use alter table with identity seed
ALTER TABLE tblStock alter column StockID Numeric IDENTITY (1, 1)
how the p[rimary key affects
Please help me"
View 1 Replies
View Related
Sep 13, 2007
How to alter a table name by using Query Analyser
i tried like this..
ALTER TABLE of_info_grp
RENAME TO stp_info_grp_map
It is giving an error like this
Server: Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'TO'.
Some one help on this
View 2 Replies
View Related
Jul 23, 2005
Hi,I'm trying to write a function check if a column exists on a table, andcreates it if it doesn't. The line that the query analyzer is citingis noted. It seems unhappy taking variables in the ALTER TABLEcommand. I can think of a hack around this, but I'm hoping there's abetter way? Muchas gracias in advance :)-DJCode followsCREATE FUNCTION fieldCreator(@TableName varchar(20),@FieldName varchar(20))RETURNS BITASBEGINif (EXISTS (SELECT count (objname)FROM ::fn_listextendedproperty (NULL, 'user', 'dbo', 'table',@TableName, 'column', @FieldName)GROUP BY objname))BEGINALTER TABLE @TableName ADD @FieldName int DEFAULT 4 --ERRORS HERE!!!EXEC sp_addextendedproperty 'caption', 'Created by script foranalysis', 'user', dbo, 'table', @TableName, 'column', @FieldNamereturn 1ENDreturn 0ENDGO
View 8 Replies
View Related
Aug 18, 2006
I used the MS Access 2000 Upsize wizard to create a Client/serverapplication. After the wizard ran, the original table names had becomethe linked tables and then there were duplicates of the the tablesnamed xxx_local.I realized later that I needed to add some fields to a table andcouldn't do that in Access (couldn't edit the linked tables). So I usedthe Query Analyzer and created a script to add the fields to my table.It looked fine in Query Analyzer, but back in Access the fields wereadded to xxx_local and not xxx, the linked table. My forms and reportsare built on xxx, not xxx_local.How do I do this correctly?Jane
View 2 Replies
View Related
Jan 28, 2008
I am trying to insert some new rows in the table tbl_3, but the problem is that I don't know how to go along with the ID column. I want to insert new rows so that it gets appended at the end and new ID is automatically generated.
Looks like this had to be done while creating the table. The original table has the id assigned as 'Identity', but I have imported this table to my database and now it does not show that property in the ID column.
The Insert code that I am using is as follows and the tbl_3 has same no. of columns except it also has id.
Can I alter table without touching the previous IDs? The ids start at 28118 and ends at 28300.
Code Snippet
INSERT INTO [dbo].[tbl_3]
(3_name
,3_sort
,3_active
,3_display
,3_date)
select _MANUFACTURERNAME , 1, 1, 'True',
GETDATE()
from dbo._MANUFACTURERS where upper(_MANUFACTURERNAME) not in (
select Upper(3_name) from dbo.tbl_3 join
dbo._MANUFACTURERS on Upper(3_name) = Upper(_MANUFACTURERNAME))
And the error it is returning to me is
Msg 515, Level 16, State 2, Line 2
Cannot insert the value NULL into column '3_id', table '.dbo.tbl_3'; column does not allow nulls. INSERT fails.
The statement has been terminated.
View 2 Replies
View Related
Mar 18, 2008
hi,
i have table having just two columns. One of columns is defines as nchar(5).
Want to alter table like
ALTER TABLE [dbo].[TestTable] ALTER COLUMN [Something] [nchar] (2)
COLLATE Latin1_General_CI_AS NOT NULL
GO
?
This script runs without problem till i have no data in table. When i add one row, this script fails with
Msg 8152, Level 16, State 13, Line 1
String or binary data would be truncated.
The statement has been terminated.
When i change the table in design mode, it says that data will be truncated and do the change (with truncating).
So is there any possibility (a switch or whatever) to update this table by script with letting engine truncate data?
Thanks for any response
Lubos
View 8 Replies
View Related