SQL Insert - String or binary data would be truncated for INT values - sql

I'm getting the "String or binary data would be truncated" error when trying to insert integers to one of my tables.
I've read several post about the length of the column vs the length of the value one is inserting, but it doesn't seem to be my case once the columns are all int or smallint type and the values are all maximum two digits.
The table structure is the following:
CREATE TABLE [tblvUserLocation] (
[User_Location_ID] [int] IDENTITY (1, 1) NOT NULL ,
[Location_ID] [int] NULL ,
[Line_Type_ID] [int] NULL ,
[User_ID] [int] NULL ,
[Active] [smallint] NULL CONSTRAINT [DF_tblvUserLocation_Active] DEFAULT (1),
[Last_Updated] [smalldatetime] NULL CONSTRAINT [DF_tblvUserLocation_Last_Updated] DEFAULT (getdate()),
[Last_Updated_By] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_tblvUserLocation_Last_Updated_By] DEFAULT (suser_sname())
) ON [PRIMARY]
GO
The insert I'm trying to run is the following:
insert into tblvUserLocation (Location_ID, Line_Type_ID, [User_ID], Active)
values (20, 2, 41, 1)
And the error I'm getting is the following:
Server: Msg 8152, Level 16, State 2, Line 1 String or binary data
would be truncated. The statement has been terminated.
If that makes any difference, I'm using SQL Server 2000.
Please let me know what your thoughts are.
Thanks!

Looks like the problem comes from your [DF_tblvUserLocation_Last_Updated_By] constraint.
It's pulling the current username which is more than likely longer than the length of your [Last_Updated_By] column VARCHAR(10).
Update your DDL to:
[Last_Updated_By] [varchar] (128)

Related

Need to have a Trigger on Table with Encrypted Column in SQL Server that inserts a new record for each update into Archive Table

I have a table similar to following schema in SQL Server 2017:
Table Sample in the main database where TaxID column is encrypted using SQL Server "Always Encrypted" feature:
CREATE TABLE [dbo].[Sample]
(
[CreatedDt] [smalldatetime] NOT NULL,
[LastModDt] [smalldatetime] NOT NULL,
[CompanyID] [int] IDENTITY(1,1) NOT NULL,
[CompanyName] [varchar](250) NOT NULL,
[CompanyTaxName] [varchar](250) NULL,
[TaxID] [varchar](15) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY =
[CEK_Auto1], ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL,
[Active] [bit] NOT NULL
)
Then we have another table with same schema in archive database for history purposes with TaxID encrypted.
This is the table Sample in the Main_Archive database:
CREATE TABLE [dbo].[Sample]
(
[CreatedDt] [smalldatetime] NOT NULL,
[LastModDt] [smalldatetime] NOT NULL,
[CompanyArchiveID] [int] IDENTITY(1,1) NOT NULL,
[CompanyID] [int] IDENTITY(1,1) NOT NULL,
[CompanyName] [varchar](250) NOT NULL,
[CompanyTaxName] [varchar](250) NULL,
[TaxID] [varchar](15) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY =
[CEK_Auto1], ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL,
[Active] [bit] NOT NULL
)
Now, we want to have a trigger on the main Sample table that inserts a new record into the archive Sample table for every update.
The trigger for the Sample table in the main database is as follows:
CREATE TRIGGER [dbo].[tr_iud_Sample]
ON [dbo].[Sample]
FOR INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON
DECLARE #CurrDt AS SMALLDATETIME
SELECT #CurrDt = GETDATE()
DECLARE #CurrYear AS INT
SELECT #CurrYear = YEAR(#CurrDt)
UPDATE Sample
SET LastModDt = #CurrDt,
CreatedDt = CASE WHEN d.CompanyID IS NULL THEN #CurrDt ELSE Sample.CreatedDt END
FROM inserted i WITH (NOLOCK)
LEFT JOIN deleted d WITH (NOLOCK) ON d.CompanyID= i.CompanyID
WHERE Sample.CompanyID = i.CompanyID
INSERT INTO [Main_Archive].[dbo].Sample
SELECT CreatedDt, LastModDt, CompanyID, CompanyName, CompanyTaxName, TaxID, Active
FROM deleted
END
ALTER TABLE [dbo].[Sample] ENABLE TRIGGER [tr_iud_Sample]
GO
ALTER TABLE [dbo].[Vendor] DISABLE TRIGGER [tr_iud_Sample]
GO
But this fails and I get this error:
Msg 4920, Level 16, State 0, Line 50
Operand type clash: varchar(15) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'NCI_COMMON') collation_name = 'Latin1_General_BIN2' is incompatible with varchar
Is there a way to have a trigger on encrypted table and if so, how to achieve the
desired functionality?
Also, if SQL Server currently does not support that, is there any work around to achieve that?
Thank you in advance
As you are using Always Encrypted your SQL Server version System-Versioned Temporal Tables.
You can make your table system-versioned and leave the work of maintaining the history to the SQL Server Engine (also, when you are changing your table design, the engine will mitigate the changes to the history table).
Temporal tables can be queried using special clauses and bring to you new ways for analyzing historical data.
One disadvantage I have faced is that the history table columns must match the target table ones - so, if you need to have a ModifiedBy column in the history, you must change your application to populate such value in the original table.

How to insert varchar (date) to DateTime field in SQL table

I need to write an insert query to insert Date(string) to a DateTime field.
This is my table
CREATE TABLE [dbo].[TSTKSInterfaceRun](
ID INT IDENTITY(1,1),
AttendanceDate [datetime] NULL,
DateOfInterfaceRun [datetime] NULL,
TotalRecords [decimal](4,2) NULL,
Company [varchar](200) NULL
) ON [PRIMARY]
I have tried using this query
Insert into [TSTKSInterfaceRun] (AttendanceDate,DateOfInterfaceRun,TotalRecords,Company) VALUES(CONVERT(Datetime, '2017-05-01 18:01:00', 120),CONVERT(Datetime, '2017-05-01 23:00:00', 120),1500,'SANCO')
but not working.
Error show as
Arithmetic overflow error converting int to data type numeric.
in SSMS.
I need a query to insert a string(date) to DateTime column in SQL table
Thanks in advance
Your value 1500 is too large for a scale (4) and the precision(2). With (4,2) the max digits is 4 with 2 being decimal places. The maximum number that this field can hold is 99.99

Got error while inserting Dataset into a database Table

This is the error
String or binary data would be truncated.
The data for table-valued parameter "#tblCustomers" doesn't conform to the table type of the parameter. SQL Server error is:
Msg 8152, state: 10
The statement has been terminated.
Here is the user-defined table type
CREATE TYPE [dbo].[recType] AS TABLE
(
[refid] [int] NULL,
[fromid] [varchar](13) NULL,
[toid] [varchar](13) NULL,
[message] [int] NULL,
[status] [varchar](13) NULL,
)
Here is the stored procedure
CREATE PROCEDURE [dbo].[SP_INSERT_RECVSMS]
#tblCustomers recType READONLY
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO RecieveSMS(Refid, fromID, Toid, message, status)
SELECT
refid, fromid, toid, message, status
FROM #tblCustomers
END
Error message is very clear. Target/source table column is to small to hold string value.
Change the size for string columns to appropriate values:
[fromid] [varchar](13) NULL
--
[fromid] [varchar](xxx) NULL,

Error Creating Database Diagram in SSMS 2012

When I attempt to create a database diagram, I get the following error:
Cannot insert the value NULL into column 'diagram_id', table 'MyDB.dbo.sysdiagrams'; column does
not allow nulls. INSERT fails.
The statement has been terminated.
The 'sp_creatediagram' procedure attempted to return a status of NULL, which is not allowed. A status of
0 will be returned instead. (.Net SqlClient Data Provider)
I am using SSMS 2012.
The database is set at a compatibility level of SQL Server 2012 (110)
##Version is Microsoft SQL Server 2012 - 11.0.5343.0 (X64)
Your problem is the diagram_ID when the table was created probably looked something like this
CREATE TABLE <table_name>
( diagram_ID INT NOT NULL PRIMARY KEY,
n...,
)
This basically means that a NULL value cannot be inserted into that column because of the NOT NULL condition. So an insert statement like:
INSERT INTO <table_name>
(Diagram_ID, n...,)
VALUES
(NULL, n...,)
Would fail because of the NULL you would need to have a value in there like (since I called it an integer):
INSERT INTO <table_name>
(Diagram_ID, n...,)
VALUES
(23, n...,)
The column may also be an indentity column in which case you have no controll over what can be inserted into the table.
Go to system tables and look for systemdiagrams table, and turn to YES the "indentity Specification" property for the field diagram_id
Hope this will help you, this script solved my issues
DROP TABLE dbo.sysdiagrams;
GO
CREATE TABLE [dbo].[sysdiagrams]
(
[name] [sysname] NOT NULL,
[principal_id] [int] NOT NULL,
[diagram_id] [int] IDENTITY(1,1) PRIMARY KEY,
[version] [int] NULL,
[definition] [varbinary](max) NULL,
CONSTRAINT [UK_principal_name] UNIQUE ([principal_id],[name])
);
GO
EXEC sys.sp_addextendedproperty
#name=N'microsoft_database_tools_support',
#value=1 ,
#level0type=N'SCHEMA',
#level0name=N'dbo',
#level1type=N'TABLE',
#level1name=N'sysdiagrams';
GO

Triggering a timestamp update

For every INSERT, how do I populate my DateStamp field with the current datetime?
I've created an error output table for my SSIS task:
Here's the table:
CREATE TABLE [dbo].[gbs_CRMErrorOutput](
[ID] [uniqueidentifier] NULL,
[ErrorCode] [nvarchar](50) NULL,
[ErrorColumn] [nvarchar](500) NULL,
[CrmErrorMessage] [nvarchar](max) NULL,
[targetid] [uniqueidentifier] NULL,
[subordinateid] [uniqueidentifier] NULL,
[DateStamp] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Please note that I do not have an auto-increment or any key in the table.
I'm also wondering what would be a best practice for this?
Here is an example of using not null with a default. In your real table you may want to name your default constraint. If you define the constraint inline like this it will still be named but it will be automatically assigned.
CREATE TABLE #MyTable
(
MyID INT IDENTITY NOT NULL,
SomeValue VARCHAR(10),
DateCreated DATETIME NOT NULL DEFAULT GETDATE()
)
INSERT #MyTable(SomeValue)
VALUES ('Value1')
--This next line just waits for 1 second.
--This will demonstrate multiple inserts at different times so you can the values change
WAITFOR DELAY '00:0:01'
INSERT #MyTable(SomeValue)
VALUES ('Value2')
SELECT *
FROM #MyTable
DROP TABLE #MyTable
Two good options:
1) Create a DEFAULT CONSTRAINT on your table with GETDATE() specified for your column (good example here). Within SSIS, do not map any value to that column - leave it as Ignore. Make sure that Keep Nulls is not checked. Note that you might have to fiddle with the settings of your OLE DB Destination - uncheck Identity Insert if there's a problem. I've also seen cases where the column had to allow NULLs - that only affects certain scenarios.
2) Add a Derived Column transformation to your data flow, setting it up to add a new column to the flow. I usually use the System::StartTime variable here, so that all records inserted during a single ETL run will share the same inserted date, but you could just as easily use the SSIS function GETDATE().
Map the new column you just created to your OLE DB Destination.