Search code examples
sql-serversql-insertcreate-table

Msg 8152 String or binary data would be truncated


I know this has been asked before, but none of the answers are fixing the issue, need another set of eyes. I'm trying to create a table and seed it with some values. I don't have any value constraints so I'm not sure why I'm getting the error I'm getting.

CREATE TABLE [dbo].[AvailableTime]
(
    [Id] [INT] IDENTITY(1,1) NOT NULL,
    [TimeString] [NCHAR] NOT NULL,
    [TimeValue] [NCHAR] NOT NULL,
    [CompanyId] [INT] NOT NULL,
    [CompanyName] [NVARCHAR](MAX) NULL,
    [LocationId] [INT] NOT NULL,
    [LocationName] [NVARCHAR] NOT NULL,
    [IsClaimed] [BIT] NOT NULL,

    CONSTRAINT [PK_AvailableTime] 
        PRIMARY KEY CLUSTERED ([Id] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                          ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

INSERT INTO dbo.AvailableTime (TimeString, TimeValue, CompanyId, CompanyName, 
                               LocationId, LocationName, IsClaimed) 
VALUES ('2019-01-07T00:00:00', '12:00 AM', 1, 'Company', 
        2, 'Inver Grove', 'FALSE');

Solution

  • You should never specify a CHAR, VARCHAR, NCHAR or NVARCHAR column (or variable, or parameter) without specifying an explicit length!

    If you omit the specific length, in some cases you'll end up with variable or column of exactly ONE character of length! That's typically NOT what you want!

    ALSO: why are you storing TimeString and TimeValue as NCHAR?? Doesn't make any sense - use the most appropriate datatype - and here, that would be DATETIME2(n) and TIME.

    So define your table like this:

    CREATE TABLE [dbo].[AvailableTime]
    (
        [Id] [INT] IDENTITY(1,1) NOT NULL,
        [TimeString] DATETIM2(0) NOT NULL,
        [TimeValue] TIME(0) NOT NULL,
        [CompanyId] [INT] NOT NULL,
        [CompanyName] [NVARCHAR](MAX) NULL,
        [LocationId] [INT] NOT NULL,
        [LocationName] [NVARCHAR](100) NOT NULL,
        [IsClaimed] [BIT] NOT NULL,
    

    and you should be fine.