Insert query, string or binary data would be truncated - sql-server

Why does this keep happening? The first 2 data types are Int. The 'Games' is DateTime. The last is VarChar. Why is it not executing successfully
CREATE TABLE JaretSchedule
(
FieldID int Primary,
TeamID int Foreign,
Games DateTime,
TeamsPlaying varChar
);
INSERT INTO [dbo].[JaretsSchedule]
([FieldID]
,[TeamID]
,[Games]
,[TeamsPlaying])
VALUES('1', '1', '2012-01-20 12:00:00', 'Roadrunners v.s. Cheetahs');
Error Message: String or binary data would be truncated. The statement has been terminated

Because ,you have exceeded the max size of field,
ALTER TABLE JaretsSchedule ALTER COLUMN TeamsPlaying nvarchar(1000);

The default length of varchar when used as a column data type is 1.
varchar [ ( n | max ) ] Variable-size string data
. . .
When n isn't specified in a data definition or variable declaration
statement, the default length is 1. If n isn't specified when using
the CAST and CONVERT functions, the default length is 30.
char and varchar (Transact-SQL)
So you need so set a max length for the column. EG
use tempdb
go
drop table if exists JaretsSchedule
go
create table JaretsSchedule
(
FieldId int,
TeamID int,
Games datetime,
TeamsPlaying varchar(255)
)
go
insert into JaretsSchedule(FieldId,TeamID,Games,TeamsPlaying)
values (1,1,'2012-01-20 10:00:00','Roadrunnersv.s.Cheetahs')

Related

Error when I try to convert string column to float column

I have a table with a column A.
I would like to change the datatype from string to float.
My column A looks like this:
A
143
1,440
19,630
12
...
When I try to run my code:
ALTER TABLE [Table1]
ALTER COLUMN [A] FLOAT
I always get this error:
Error converting data type varchar to float.
It is clear in error that varchar value is not converting into float. Since , is not allowed in int, float, decimal type values, so first need to replace your , .
Instead of this you may try this.
update table set A = Replace( A, ',', '' )
Or
update table set A = Replace( A, ',', '.' )
Whichever condition suits you better.
After that convert your column.
ALTER TABLE [Table1]
ALTER COLUMN [A] FLOAT

Conversion failed when converting the varchar value 'SAT' to data type int

I have a table ConsoleGames wherein all columns are of type varchar(50). When I try to create a new table console_games by amending existing datatypes by using the query:
CREATE TABLE console_games
(
game_rank integer,
game_name varchar(1200),
platform_name varchar(1200),
game_year integer,
genre varchar(200),
publisher varchar(1200),
na_sales float,
eu_sales float,
jp_sales float,
other_sales float
)
INSERT INTO console_games
SELECT *
FROM [dbo].[RAWConsoleGames]
I get the following error message:
Msg 245, Level 16, State 1, Line 17
Conversion failed when converting the varchar value 'SAT' to data type int.
When I look into the data in the table the value 'SAT' is in a column for which I am not changing the datatype. 'SAT' value exists in the Platform column which is of varchar type and I am not trying to change the type to int.
Any help will be appreciated.
Thanks
Clearly 'SAT' is not and will never convert to an INT.
Always best to specify the columns to insert ... things change
Now, if the source data is suspect, add a try_convert(). If the conversion fails, a null value will be returned
I don't know the column names of your source, so I substituted SomeColN
INSERT INTO console_games
SELECT try_convert(integer ,SomeCol1)
,try_convert(varchar(1200),SomeCol2)
,try_convert(varchar(1200),SomeCol3)
,try_convert(integer ,SomeCol4)
,try_convert(varchar(200) ,SomeCol5)
,try_convert(varchar(1200),SomeCol6)
,try_convert(float ,SomeCol7)
,try_convert(float ,SomeCol8)
,try_convert(float ,SomeCol9)
,try_convert(float ,SomeCol10)
FROM [dbo].[RAWConsoleGames]
Just for fun, try:
Select try_convert(int,'SAT')
Select try_convert(int,'25.25')
Select try_convert(int,'25')
You should always define the list of columns you're inserting into, and you should also always define the list of columns you're selecting from. Furthermore, I'd recommend to explicitly do any type conversions instead of leaving that up to SQL Server - if you do it yourself, you know when and what you're doing.
So I'd write that statement like this:
-- **DEFINE** the list of columns you're inserting into
INSERT INTO console_games (rank, name, Platform, year, genre, publisher,
sales, eu_sales, jp_sales, other_sales)
-- **DEFINE** the list of columns you're selecting, and any conversions
SELECT
game_rank, game_name, platform_name,
CAST(game_year AS VARCHAR(50)), genre,
publisher,
CAST(na_sales AS VARCHAR(50)),
CAST(eu_sales AS VARCHAR(50)),
CAST(jp_sales AS VARCHAR(50)),
CAST(other_sales AS VARCHAR(50))
FROM
[dbo].[RAWConsoleGames]

Error converting varchar to bigint (CONVERT, SUBSTRING, PATINDEX)

In the following sproc I'm having troubles converting my id into a bigint when returning. The id is of the form {letters}{numbers}, where {letters} can be 2 or 3 characters long and {numbers} can be any length. I'm trying to first grab the numbers from my id and then convert these to bigint and return this in place of the id field. My understanding for SUBSTRING is that I can use PATINDEX to get the first index where a number is encountered and grab the substring from that index. I set length to 50 only because I don't know how long a person's actual id is and 50 is the max length for [id] to begin with.
ALTER PROCEDURE [dbo].[GetSummoner]
#Id varchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT
CONVERT(bigint, SUBSTRING([id], (PATINDEX('%[^0-9]%', [id])), 50)) AS id
,[name]
,[modify_date]
,[profile_icon_id]
,[revision_date]
,[summoner_level]
FROM [Summoners]
WHERE [id]=#Id
END
Edit: Error message: "Error converting data type varchar to bigint."
You are using the wrong PATINDEX. remove the ^ char.
Also, whenever you encounter problems like this the easy way to debug it is running the select without the convert and see what you get.
CONVERT(bigint, SUBSTRING([id], (PATINDEX('%[0-9]%', [id])), 50)) As id

Short guid in SQL Server / converting from a character string to uniqueidentifier

I need to create a column witch will contain short guid. So I found out something like this:
alter table [dbo].[Table]
add InC UNIQUEIDENTIFIER not null default LEFT(NEWID(),6)
But I get the error:
Conversion failed when converting from a character string to uniqueidentifier.
I've been trying
LEFT(CONVERT(varchar(36),NEWID()),6)
and
CONVERT(UNIQUEIDENTIFIER,LEFT(CONVERT(varchar(36),NEWID()),6))
But I am still getting the same error.
There is no such thing as "short guid". Guid, or uniqueidentifier is a 16 byte data type. You can read about it in MSDN. It means that the length must always be 16 bytes and you cannot use 6 characters as you are trying to do.
In the same MSDN article you can find description how you can initialize this type:
A column or local variable of uniqueidentifier data type can be
initialized to a value in the following ways:
By using the NEWID function.
By converting from a string constant in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, in which each x is a
hexadecimal digit in the range 0-9 or a-f. For example,
6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid uniqueidentifier
value.
In your case you are trying to convert only 6 characters to uniqueidentifier which obviously fails.
If you want to use just 6 characters, just use varchar(6):
alter table [dbo].[Table]
add InC varchar(6) not null default LEFT(NEWID(),6)
Keep in mind that in this case this guid is not guaranteed to be unique.
Using CRYPT_GEN_RANDOM instead of NEWID can improve random distribution of the string.
SELECT LEFT(CAST(CAST(CRYPT_GEN_RANDOM(16) AS UNIQUEIDENTIFIER) AS VARCHAR(50)), 6)
I just made this one since I couldn't find a good answer on the internet.
Please keep in mind this is a 64 bit representation of a 128bit value, so it has twice the collision possibilities that a real GUID would have. Does not handle 0.
Function takes a NEWID value: 6A10A273-4561-40D8-8D36-4D3B37E4A19C
and shortens it to : 7341xIlZseT
DECLARE #myid uniqueidentifier= NEWID()
select #myid
DECLARE #bigintdata BIGINT = cast(cast(reverse(NEWID()) as varbinary(max)) as bigint)
DECLARE #charSet VARCHAR(70) = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
DECLARE #cBase int = LEN(#charSet)
DECLARE #sUID varchar(22) = ''
DECLARE #x int
WHILE (#bigintdata <> 0)
BEGIN
SET #x = CAST(#bigintdata % #cBase as INT) + 1
SET #bigintdata = #bigintdata / #cBase
SET #sUID = SUBSTRING(#charSet, #x, 1) + #sUID;
END
SELECT #sUID

Computed column value not the same as Scalar Function it uses

I have a Table with a computed column that uses a scalar function
CREATE FUNCTION [dbo].[ConvertToMillimetres]
(
#fromUnitOfMeasure int,
#value decimal(18,4)
)
RETURNS decimal(18,2)
WITH SCHEMABINDING
AS
BEGIN
RETURN
CASE
WHEN #fromUnitOfMeasure=1 THEN #value
WHEN #fromUnitOfMeasure=2 THEN #value * 100
WHEN #fromUnitOfMeasure=3 THEN #value * 1000
WHEN #fromUnitOfMeasure=4 THEN #value * 25.4
ELSE #value
END
END
GO
The table has this column
[LengthInMm] AS (CONVERT([decimal](18,2),[dbo].[ConvertToMillimetres]([LengthUnitOfMeasure],[Length]))) PERSISTED,
Assuming that the [Length] on the Table is 62.01249 and [LengthUnitOfMeasure] is 4 the LengthInMm computed value comes with 1575.11 but when i run the function directly like
SELECT [dbo].[ConvertToMillimetres] (4, 62.01249) GO
It comes with 1575.12
[Length] column is (decimal(18,4, null))
Can anyone tell why this happens?
I'm not sure this really counts as an answer, but you've perhaps got a problem with a specific version of SQL?
I just had a go at replicating it (on a local SQL 2014 install) and got the following:
create table dbo.Widgets (
Name varchar(20),
Length decimal(18,4),
LengthInMm AS [dbo].[ConvertToMillimetres] (4, Length) PERSISTED
)
insert into dbo.Widgets (Name, Length) values ('Thingy', 62.01249)
select * from dbo.Widgets
Which gives the result:
Name Length LengthInMm
-------------------- --------------------------------------- ---------------------------------------
Thingy 62.0125 1575.12
(1 row(s) affected)
Note that your definition uses [LengthInMm] AS (CONVERT([decimal](18,2),[dbo].[ConvertToMillimetres]([LengthUnitOfMeasure],[Length]))) PERSISTED, but that doesn't seem to make a difference to the result.
I also tried on my PC (Microsoft SQL Server 2012 - 11.0.2100.60 (X64)). Works fine:
CREATE TABLE dbo.data(
LengthUnitOfMeasure INT,
[Length] decimal(18,4),
[LengthInMm] AS (CONVERT([decimal](18,2),[dbo].[ConvertToMillimetres]([LengthUnitOfMeasure],[Length]))) PERSISTED
)
INSERT INTO dbo.data (LengthUnitOfMeasure, [Length])
SELECT 4, 62.01249
SELECT *
FROM dbo.data
/*
RESULT
LengthUnitOfMeasure Length LengthInMm
4 62.0125 1575.12
*/
I think, I found the answer:
Lets see what you are saying:
There is a column with decimal(18,4) data type.
There is a calculated column which depend on this column.
The result differs when you select the calculated field and when you provide the same result manually. (Right?)
Sorry, but the input parameters are not the same:
The column in the table is decimal(18,4). The value you are provided manually is decimal(7,5) (62.01249)
Since the column in the table can not store any values with scale of 5, the provided values will not be equal. (Furthermore there is no record in the table with the value of 62.01249 in the Length column)
What is the output when you query the [Length] column from the table? Is it 62.0124? If yes, then this is the answer. The results can not be equal since the input values are not equal.
To be a bit more specific: 62.01249 will be casted (implicit cast) to 62.0125.
ROUND(25.4 * 62.0124, 2) = 1575.11
ROUND(25.4 * 62.0125, 2) = 1575.12
EDIT Everybody who tried to rebuild the schema made the same mistake (Including me). When we (blindly) inserted the values from the original question into our instances, we inserted the 62.01249 into the Length column -> the same implicit cast occured, so we have the value 62.0125 in our tables.

Resources