SQL Column will not allow entry after being altered - sql

I have a SQL table that has a column "Stamp" the was originally setup as nchar(10). The data that was entered in this field was only 9 characters long (ie. XX111.jpg) However, I have changed the format of the data being entered. It is now XX-XXX111.jpg. I ran this alter statement to increase the column size:
Alter Table tblData
Alter Column Stamp nvarchar(50)
Afterwards I would run an update statement to update the NULL values in the database:
Update tblData Set Stamp = 'XX-XXX111.jpg' where Updated > '2014-08-01' and Stamp is null
When I do this I get the following error:
(22 row(s) affected)
Msg 8152, Level 16, State 13, Procedure ChangedMECTrigger, Line 31
String or binary data would be truncated.
The statement has been terminated.
I don't understand how this is not working. Where am I going wrong?

You apparently have a trigger on the table:
ChangedMECTrigger
You need to update the data length on this too.
You can find those in SSMS here:

there's a trigger tied to tblData called ChangedMECTrigger. Something in the trigger's logic is causing the error. You could temporarily disable the trigger prior to running your update tblData... statement like this:
disable trigger ChangedMECTrigger on tblData
Update tblData Set Stamp = 'XX-XXX111.jpg' where Updated > '2014-08-01' and Stamp is null
enable trigger ChangedMECTrigger on tblData
or you could look at the trigger's code to find the issue. Chances are there's something in the trigger using nchar(10) still and needs to be updated to nvarchar(50).

Related

Cannot add NOT NULL constraint [duplicate]

So I want to change a column in my SQL Server database to not allow nulls, but I keep getting an error. this is the sql statement I am using:
alter table [dbo].[mydatabase] alter column WeekInt int not null
and this is the error I am getting :
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'WeekInt', table 'CustomerRadar.dbo.tblRWCampaignMessages'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
I'm pretty sure my sql is right, and there are no nulls currently in the column I am trying to change so I am really not sure as to what is causing the problem. Any ideas? I'm stumped.
Clearly, the table has NULL values in it. Which you can check with:
select *
from mydatabase
where WeekInt is NULL;
Then, you can do one of two things. Either change the values:
update mydatabase
set WeekInt = -1
where WeekInt is null;
Or delete the offending rows:
delete from mydatabase
where WeekInt is null;
Then, when all the values are okay, you can do the alter table statement.
If you are trying to change a column to not null, and you are getting this error message, yet it appears the column has no nulls, ensure you are checking for is null and not = null (which gives different results).
Select * from ... where column is null
instead of
Select * from ... where column = null
I am adding this because it tripped me up and took a while to resolve.
This will work. You should send a default value, then it will change all the previous record to -1 in this example.
alter table [dbo].[mydatabase] alter column WeekInt int not null DEFAULT '-1';

Truncate SQL varchar column

I currently have a column of varchar(3000). I want to reduce that to 400 characters.
When I execute this query:
ALTER TABLE [dbo].[App]
ALTER COLUMN SpecialInstructions VARCHAR(400) NOT NULL
I get this error:
Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated.
How do I set where previous data in that column would just be cut off? I'm using a development database, so it wouldn't matter if I was losing information. Or is there a better way to do this? Thanks in advance.
update [dbo].[App]
set SpecialInstructions = left(SpecialInstructions, 400)
You can optionally add a WHERE clause to make sure only too long values are shortened:
where len(SpecialInstructions) > 400
This is to reduce the number of rows updated. Keeps transaction smaller, incl write-sets.

Early execution of "sp_rename" causes query to fail

I'm having a strange problem with an MSSQL Query that I'm trying to run in Microsoft SQL Server 2014. It is an update script for my database structure. It should basically rename a Column (from Price to SellingPrice) of a Table after its content was merged to another one.
USE db_meta
GO
DECLARE #BakItemPrices TABLE
(
ItemNum int,
Price int,
CashPrice int
)
-- backup old prices
insert into #BakItemPrices
select ItemNum, Price from dbo.ItemInfo
-- merge into other table
alter table ShopInfo
add column Price int NOT NULL DEFAULT ((0))
update ShopInfo
set ShopInfo.Price = i.Price
from ShopInfo s
inner join #BakItemPrices i
on s.ItemNum = i.ItemNum
GO
-- rename the column
exec sp_rename 'ItemInfo.Price', 'SellingPrice', 'COLUMN' -- The Debugger executes this first
GO
This query always gave me the error
Msg 207, Level 16, State 1, Line 13
Invalid column name 'Price'.
I couldn't understand this error until I debugged the query. I was amazed as I saw that the debugger wont even hit the breakpoint I placed at the backup code and says that "its unreachable because another batch is being executed at the moment".
Looking further down I saw that the debugger instantly starts with the exec sp_rename ... line before it executes the query code that I wrote above. So at the point my backup code is being executed the Column is named SellingPrice and not Price which obviously causes it to fail.
I thought queries get processed from top to bottom? Why is the execute sequence being executed before the code that I wrote above?
Script is sequenced from top to down. But some changes to schema is "visible" after the transaction with script is committed. Split your script into two scripts, it can help.

Set DEFAULT value on a column, based on the compute of another column

EDIT:I'M USING SQL-Oracle Database 10g
I need to set one column DATE value (loan_due), based on another DATE column(loan_date).
The thing is, "loan_due" has to be exactly the next month of "loan_date" and the DAY has to be 5.
EXAMPLE:
IF loan_date IS '12/06/14', the loan_due HAS TO BE '05/07/14'(This have to take place,just right after I insert loan_Date)
IF loan_date IS '01/09/14', the loan_due HAS TO BE '05/10/14'
I think a TRIGGER could help, but when i try, I only get "Mutating table" errors.. because the trigger try to DML the table in which is working.
If you are needing to set a column on the same row that's being INSERTed or UPDATEd, then a BEFORE INSERT or BEFORE UPDATE trigger is the way to go.
In the body of the trigger, for MySQL you just do something like this:
SET NEW.loan_due = LAST_DAY(NEW.loan_date) + INTERVAL 5 DAY;
After the trigger is fired, When the statement proceeds, the loan_due column will have the value that was set in the trigger, and the INSERT or UPDATE will proceed using that value.
For Oracle, it's much the same. In the body of the BEFORE INSERT FOR EACH ROW trigger, assign a value to the column. The assignment syntax is different in PL/SQL:
NEW.loan_due := expr ;
Where expr is an expression that returns the 5th day of the month, following NEW.loan_date.

IDENTITY_INSERT error while trying to insert data into table

I want to copy data from a table named ActionType inside a database TD_EDD, into another table named ActionType inside another database DsVelocity.
I have written the following query:
INSERT INTO [DsVelocity].[dbo].[ActionType]
([ActionTypeID]
,[ActionTypeName]
,[ActiveStatus])
SELECT [ActionTypeID], [ActionType], [Active/Deactive]
FROM [TD_EDD].[dbo].[ActionType]
GO
Whenever I'm trying to do this, I'm getting the following error:
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'ActionType' when IDENTITY_INSERT is set to OFF.
I don't understand what's wrong and why I'm getting this error?
Note that I'm using Microsoft SQL Server 2008 R2.
This means that when you insert data into target table, you will have conflicting ids. Most likely ActionTypeId column
to Fix it use
INSERT INTO [DsVelocity].[dbo].[ActionType]
([ActionTypeName]
,[ActiveStatus])
SELECT [ActionType], [Active/Deactive]
FROM [TD_EDD].[dbo].[ActionType]
GO
Well, lets assume from the message that ActionTypeID is an IDENTITY Column. You cannot isert values into this column as it is auto generate, uless you use IDENTITY_INSERT
Allows explicit values to be inserted into the identity column of a
table.
At any time, only one table in a session can have the IDENTITY_INSERT
property set to ON. If a table already has this property set to ON,
and a SET IDENTITY_INSERT ON statement is issued for another table,
SQL Server returns an error message that states SET IDENTITY_INSERT is
already ON and reports the table it is set ON for.
If the value inserted is larger than the current identity value for
the table, SQL Server automatically uses the new inserted value as the
current identity value.
The setting of SET IDENTITY_INSERT is set at execute or run time and
not at parse time.
So you would have to do something like
SET IDENTITY_INSERT [DsVelocity].[dbo].[ActionType] ON
before the insert.