SELECT
#dp_all.RegistrationNumber AS 'номер устройства',
#dp_all.DeviceLocation AS 'Номер ТС',
MAX(#card_transactions.timestamp) AS 'дата валидации',
#dp_all.LastVersionReadTime AS 'дата связи'
FROM
#dp_all
INNER JOIN #card_transactions ON
#dp_all.RegistrationNumber like '%' + #card_transactions.device_reg_no
WHERE
#dp_all.DeviceLocation is not null
GROUP BY
#dp_all.RegistrationNumber,
#dp_all.DeviceLocation,
#dp_all.LastVersionReadTime
ORDER BY
#dp_all.DeviceLocation
Где:
- RegistrationNumber -bigint,
- DeviceLocation — nvarchar,
- LastVersionReadTime — datetime,
- derice_reg_no — bigint.
Anton Shchyrov
32.8k2 золотых знака28 серебряных знаков56 бронзовых знаков
задан 11 сен 2018 в 13:13
7
Есть такая штука Data type precedence. Именно из-за приоритетов вы получаете ошибку при сравнении, уже неявно приобразованной строки с bigint значением.
Второй момент, сравнивать эти поля стоит тогда когда они оба будут одного типа. Преведите первый в varchar(n)/nvarchar(n) и второй с помощью CAST или CONVERT и сравнивайте вашим подходом наздоровье.
Пример условия:
ON convert(nvarchar,#dp_all.RegistrationNumber) like '%' + convert(nvarchar,#card_transactions.device_reg_no)
ответ дан 11 сен 2018 в 13:41
Nick ProskuryakovNick Proskuryakov
3,7122 золотых знака13 серебряных знаков37 бронзовых знаков
2
- Remove From My Forums
-
Question
-
Dear
I have the issue with my SQL. I used the a variable with bigint to pass into my Select query. When I run this SQL, I received this error message «Error converting data type varchar to bigint». How can I resolve this
issue?Thanks
Khoi
Answers
-
Valiant1982,
You are running into this issue because of data type precedence. Essentially, when data is compared in sql server, data types that do not match have to be converted into the same type. This is known as implicit conversion. In
order to do this, SQL Server uses precedence rules, which only mean the data type with the greatest precedence, wins and the other data type must be converted. In your case BIGINT takes precedence over a character column therefore, SQL Server has to
do an implicit conversion of your character column to BIGINT. If any of the data in the column cant convert, you get a conversion error.Your options are to change the data type of your variable to match your column data type, or to clean your data up. You can find the bad data using the query below. Please note that you should consider changing your column data type to bigint,
if this is what you plan to use for comparison.DECLARE @t TABLE(ID VARCHAR(10)); INSERT INTO @t VALUES ('1'); INSERT INTO @t VALUES ('1A'); INSERT INTO @t VALUES ('1-)'); INSERT INTO @t VALUES ('1?41'); INSERT INTO @t VALUES ('2'); INSERT INTO @t VALUES ('3'); SELECT * FROM @t WHERE Id LIKE '%[^0-9]%'
http://jahaines.blogspot.com/
-
Proposed as answer by
Wednesday, July 14, 2010 5:59 PM
-
Marked as answer by
KJian_
Tuesday, July 20, 2010 12:25 PM
-
Proposed as answer by
- Remove From My Forums
-
Question
-
Dear
I have the issue with my SQL. I used the a variable with bigint to pass into my Select query. When I run this SQL, I received this error message «Error converting data type varchar to bigint». How can I resolve this
issue?Thanks
Khoi
Answers
-
Valiant1982,
You are running into this issue because of data type precedence. Essentially, when data is compared in sql server, data types that do not match have to be converted into the same type. This is known as implicit conversion. In
order to do this, SQL Server uses precedence rules, which only mean the data type with the greatest precedence, wins and the other data type must be converted. In your case BIGINT takes precedence over a character column therefore, SQL Server has to
do an implicit conversion of your character column to BIGINT. If any of the data in the column cant convert, you get a conversion error.Your options are to change the data type of your variable to match your column data type, or to clean your data up. You can find the bad data using the query below. Please note that you should consider changing your column data type to bigint,
if this is what you plan to use for comparison.DECLARE @t TABLE(ID VARCHAR(10)); INSERT INTO @t VALUES ('1'); INSERT INTO @t VALUES ('1A'); INSERT INTO @t VALUES ('1-)'); INSERT INTO @t VALUES ('1?41'); INSERT INTO @t VALUES ('2'); INSERT INTO @t VALUES ('3'); SELECT * FROM @t WHERE Id LIKE '%[^0-9]%'
http://jahaines.blogspot.com/
-
Proposed as answer by
Wednesday, July 14, 2010 5:59 PM
-
Marked as answer by
KJian_
Tuesday, July 20, 2010 12:25 PM
-
Proposed as answer by
Я пытаюсь преобразовать varchar в bigint, но продолжаю получать
Ошибка преобразования типа данных varchar в bigint.
Это мой синтаксис:
CASE SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr))
WHEN '-' THEN NULL
ELSE CONVERT(bigint, SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr)))
END
Это часть значения json, которое я беру подстроку из:
{
"lat": "52.650000",
"lon": "5.730000",
"name": "NAGELE",
"cmt": "PROV: FLEVOLAND, INW: -",
"desc": "PROV: FLEVOLAND, INW: -",
"sym": "Medium City"
},
{
"lat": "52.670000",
"lon": "5.600000",
"name": "URK",
"cmt": "PROV: FLEVOLAND, INW: 16489",
"desc": "PROV: FLEVOLAND, INW: 16489",
"sym": "Medium City"
},
Поэтому, когда INW: равно ‘-‘, я хочу вставить null, когда INW: например, 16489 Я хочу вставить это значение (столбец — bigint)
Я тоже пробовал вот так:
CASE SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr))
WHEN '-' THEN NULL
ELSE CAST(SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr)) AS bigint)
END
Это мой цикл для объектов JSON:
begin
declare @_StateProvinceID int = (NEXT VALUE FOR [Sequences].[StateProvinceID])
Insert into [Application].[StateProvinces] (StateProvinceID,StateProvinceCode,StateProvinceName,CountryID,SalesTerritory)
values(@_StateProvinceID,UPPER(SUBSTRING (@StateProvince, 1, 2)),@StateProvince,@_CountryID,@_SalesTerritory)
declare @_InnerJson VARCHAR(MAX) = @json
DECLARE @wpt VARCHAR(MAX);
SET @wpt = JSON_QUERY(@_InnerJson, '$.wpt');
;with cte_a as (
SELECT UPPER(SUBSTRING (@StateProvince, 1, 2))[StateProvinceCode],@StateProvince [StateProvince],* FROM
OPENJSON ( @wpt )
WITH (name varchar(max) '$.name',lat varchar(max) '$.lat',lon varchar(max) '$.lon', descr varchar(max) '$.desc'))
Insert Into [Application].[Cities] (StateProvinceID,CityName,Location,LatestRecordedPopulation)
select @_StateProvinceID,a.name,geography::Point(lat, lon, 4326),
(CASE (SELECT SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr))) WHEN '-' THEN NULL ELSE (SELECT SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr))) END)
from cte_a a
End
Кто-нибудь знает, как заставить это работать?
3 ответа
Лучший ответ
Если вы <▪позитив, что этот бит работает …
SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr))
Затем заверните его в это …
CAST(
NULLIF(
SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr)),
'-'
)
AS BIGINT
)
Просто будьте очень уверены, что ваш исходный фрагмент всегда сначала дает то, что вы хотите. Тем более, что он никогда не дает неожиданных пространств и т. Д.
< EM> Edit:
Поскольку это не работает, я могу только сделать вывод, что ваша подстрока не всегда возвращает то, что вы ожидаете.
Пожалуйста, покажите < sizesboth входные строки (descr
) < sizes и результаты следующих … (Как редактирование вашего вопроса.)
'>' + SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr)) + '<'
1
MatBailie
9 Ноя 2020 в 18:16
Что ж, вы уверены, что передаете правильные значения в функцию приведения / преобразования, но вы получаете:
Error converting data type varchar to bigint.
В таких случаях проще всего использовать функцию TRY_CONVERT. Что-то вроде этого:
CASE SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr))
WHEN '-' THEN NULL
ELSE TRY_CONVERT(bigint, SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr)))
END
Это даст вам две вещи:
- Во-первых, ваша проблема будет решена, так как если вход функции не может быть преобразован в
bigint
, это даст вамNULL
- во-вторых, вы можете изолировать значения
NULL
и посмотреть, есть ли запись, отличная от-
, которая пропущена при проверке и может привести к ошибке
0
gotqn
9 Ноя 2020 в 19:16
Поскольку вы сосредотачиваетесь на части sql, чтобы найти, что не так, я также пытаюсь помочь вам исправить sql …
Вы предоставили здесь
CASE SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr))
WHEN '-' THEN NULL
ELSE CONVERT(bigint, SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, LEN(descr)))
END
Здесь подстрока — это не то, что вы ожидаете, поэтому она не может преобразовать ее в bigint.
Ваша логика подстроки фактически возвращает строку, подобную моей локальной симуляции, как вы видите на следующем снимке экрана —
Теперь посмотрим, почему он не может преобразовать это в bigint.
Исправить можно было бы правильно контролировать длину подстроки. Если вы знаете, что число имеет длину 5 символов, тогда ваш sql можно переписать как
CASE SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, 1)
WHEN '-' THEN NULL
ELSE CONVERT(bigint, SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, 5))
END
Если длина числа неизвестна, запрос будет таким
CASE SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, 1)
WHEN '-' THEN NULL
ELSE CONVERT(bigint, SUBSTRING(descr, CHARINDEX('INW: ', descr) + 5, CHARINDEX('",', @someString,CHARINDEX('INW: ', @someString)) - CHARINDEX('INW: ', @someString) - 5)))
END
Надеюсь, вы понимаете проблему и способ ее решения в вашем реальном контексте.
-1
Raihan
9 Ноя 2020 в 18:20
Содержание
- Sql error converting varchar to bigint
- Answered by:
- Question
- Answers
- All replies
- Sql error converting varchar to bigint
- Answered by:
- Question
- Converting VARCHAR to BIGINT
- Error converting data type varchar to bigint.
- Sql error converting varchar to bigint
- Answered by:
- Question
- Answers
- All replies
Sql error converting varchar to bigint
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I have designed a SP where i need to update all the records for a table where ErrorId is not equal to the ones provided.In this stored procedure i am parsing and all the errorids delimited by ‘,’ into a varchar variable which i would be using for updating the table.On the second last line i get the error mentioned in the subject line.any help would be appreciated.
ALTER PROCEDURE [dbo] . [sp_ParseAndUpdateDetails]
@ParserString varchar ( MAX )
DECLARE @NextPos int
DECLARE @LoopCond tinyint
DECLARE @PreviousPos int
DECLARE @FlgFirst bit
DECLARE @QueryCondition varchar ( MAX )
SET @LoopCond = 1
SET @FlgFirst = 0
WHILE ( @LoopCond = 1 )
—Retrieving the Position of the delimiter
SET @NextPos = @NextPos + 1
SET @NextPos = CHARINDEX ( ‘,’ , @ParserString , @NextPos )
—Retreiving the last substring
PRINT SUBSTRING ( @ParserString , @PreviousPos + 1 ,( LEN ( @ParserString )+ 1 )- @PreviousPos )
SET @QueryCondition = @QueryCondition + ‘ AND ErrorId <> ‘ + CAST ( SUBSTRING ( @ParserString , @PreviousPos + 1 ,( LEN ( @ParserString )+ 1 )- @PreviousPos ) AS bigint )
SET @PreviousPos = @NextPos
—Retrieving the individual substrings
—Retreiving the first substring
SET @FlgFirst = 1
PRINT SUBSTRING ( @ParserString , 1 , @NextPos — 1 )
SET @QueryCondition = @QueryCondition + CAST ( SUBSTRING ( @ParserString , 1 , @NextPos — 1 ) AS bigint )
SET @PreviousPos = @NextPos
—Retreiving the internmediate substrings
PRINT SUBSTRING ( @ParserString , @PreviousPos + 1 ,( @NextPos — 1 )- @PreviousPos )
SET @QueryCondition = @QueryCondition + ‘ AND ErrorId <> ‘ + CAST ( SUBSTRING ( @ParserString , @PreviousPos + 1 ,( @NextPos — 1 )- @PreviousPos ) AS bigint )
SET @PreviousPos = @NextPos
print ‘ErrorId <>‘ + @QueryCondition
UPDATE [ESMS2_DBMS] . [dbo] . [ErrorDetails]
SET ErrorRectifyDateTime = GETDATE ()
WHERE ( NozzleId = @NozzleId ) AND ( ErrorRectifyDateTime IS NULL) AND ( ErrorId <> @QueryCondition )
Answers
Thanks friends for your replies
Finally following is the dynamic sql modified statement.
SELECT @Sql = ‘UPDATE [ESMS2_DBMS].[dbo].[ErrorDetails] ‘
SELECT @Sql = @Sql + ‘ SET ErrorRectifyDateTime = CONVERT(VARCHAR(25),GETDATE())’
SELECT @Sql = @Sql + ‘ WHERE (NozzleId = ‘ + CONVERT ( VARCHAR ( 20 ), @NozzleId ) + ‘) AND (ErrorRectifyDateTime IS NULL)’
SELECT @Sql = @Sql + ‘ AND (ErrorId NOT IN (SELECT ErrorId FROM [ESMS2_DBMS].[dbo].[‘ + @TempTable + ‘])) ‘
EXEC sp_executesql @Sql
SET @QueryCondition = @QueryCondition + ‘ AND ErrorId <> ‘ + CAST ( SUBSTRING ( @ParserString , @PreviousPos + 1 ,( LEN ( @ParserString )+ 1 )- @PreviousPos ) AS bigint )
Why would you cast the string value as bigint, then concatenate it back with a varchar data type variable? This forces SQL to do implicit data type conversions.
I’m guessing the data type for the ErrorId column is bigint. SQL cannot convert @QueryCondition from varchar to bigint b/c the variable contains characters.
Источник
Sql error converting varchar to bigint
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I have a table where the values of two columns, while saved as a four byte integer, have different real meanings depending upon the contents of a third column. Sometimes the value is an int, float, one of multiple enumerated values, version information and so on. To handle this, there are case statements within the select and this works just fine for discriminating between the various record types.
The int and float conversion code works just fine but when an enumerated value is included Sql Server has a problem with things and displays ‘Error converting data type varchar to bigint.’
The SQL script (sort of) looks like this. At the time of the select the RecordId, RecordType and DataVal2 are taken as is by the select. However, DataVal1 gets converted depending upon the contents of RecordType. In this case, a 0 indicates that DataVal1 needs to be passed to a stored procedure and the results of that (which are a float) are placed in that column of the row. Alternatively, if RecordType is a 3 then DataVal1 is an enumerated value and the script uses that as a key to get the human friendly string that corresponds to the enumerated value that corresponds to the int in DataVal1. If the RecordType is some else then the default case is called and DataVal1 comes through unmodified as an int.
So what I am guessing is happening is that the first values to come through are interpreted as an int. When the enumerated value converted to a string comes along the DataVal1 column has already been established as an int. If this assessment is correct then it would seem that the simplest solution would be to convert everything to a string. How can that be done?
Источник
Converting VARCHAR to BIGINT
February 25, 2016 at 12:03 pm
I am working on a project where I need to move values from one table (tableOriginal) into another table (tableNew). The original table has two columns EstCards / EstAccts that are stored as varchar but in the new table, we want these values stored as integer (technically bigint because some values in the original table for some reason are in the billions).
When I do the following SQL Statement (see pasted below), I am getting an error saying (this will be added to the SELECT INTO statement but for now just need to convert the varchar values to bigint and if they cannot be converted, enter zero in the new table):
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to bigint.
I am not sure what record this is breaking on to know what I am missing. Do you know of a way to check if a varchar can be converted to a number and if it cannot, I want to insert a zero or even know how to find the record that is failing the test? I really only think I need only one “WHEN” statement, but I am trying anything I can think of.
WHEN EstCards IS NULL THEN 0
WHEN LEN(EstCards) = 0 THEN 0
WHEN ISNUMERIC(EstCards) = 0 THEN 0
WHEN ISNUMERIC(EstCards) = 1 THEN CAST(EstCards AS BIGINT)
WHEN EstAccounts IS NULL THEN 0
WHEN LEN(EstAccounts) = 0 THEN 0
WHEN ISNUMERIC(EstAccounts) = 0 THEN 0
WHEN ISNUMERIC(EstAccounts) = 1 THEN CAST(EstAccounts AS BIGINT)
Источник
Error converting data type varchar to bigint.
Hello. I am creating a SP and receiving the error message while executing. This SP works fine on different servers but it cause issue on this server only.
DECLARE @HOSTNAME VARCHAR(20),
@iatebreakfast VARCHAR(100),
@BGCOLOR VARCHAR(50),
@REC VARCHAR(50),
@Priority Networks VARCHAR(10),
@free VARCHAR(20),
@total VARCHAR(20),
@free _PER VARCHAR(20),
@Chart VARCHAR(2000),
@azzedinehtmlsql VARCHAR(MAX),
@HTMLTEMP VARCHAR(MAX),
@Title VARCHAR(100),
@Lenovo VARCHAR(100),
@alenzi VARCHAR(MAX)
CREATE TABLE #MOUNTVOL (COL1 VARCHAR(500))
INSERT INTO #MOUNTVOL
EXEC XP_CMDSHELL ‘MOUNTVOL’
DELETE #MOUNTVOL WHERE COL1 NOT LIKE ‘%:%’
DELETE #MOUNTVOL WHERE COL1 LIKE ‘%VOLUME%’
DELETE #MOUNTVOL WHERE COL1 IS NULL
DELETE #MOUNTVOL WHERE COL1 NOT LIKE ‘%:%’
DELETE #MOUNTVOL WHERE COL1 LIKE ‘%MOUNTVOL%’
DELETE #MOUNTVOL WHERE COL1 LIKE ‘%RECYCLE%’
SELECT LTRIM(RTRIM(COL1)) FROM #MOUNTVOL
CREATE TABLE #DRIVES
(
DRIVE VARCHAR(500),
INFO VARCHAR(80)
)
DECLARE CUR CURSOR FOR SELECT LTRIM(RTRIM(COL1)) FROM #MOUNTVOL
OPEN CUR
FETCH NEXT FROM CUR INTO @Lenovo
WHILE @@Fetch _STATUS=0
BEGIN
SET @alenzi = ‘EXEC XP_CMDSHELL »FSUTIL VOLUME DISKFREE ‘ + @Lenovo +»»
FETCH NEXT FROM CUR INTO @Lenovo
END
CLOSE CUR
DEALLOCATE CUR
— SHOW THE EXPECTED OUTPUT
SELECT DRIVE,
SUM(CASE WHEN INFO LIKE ‘TOTAL # OF BYTES : %’ THEN CAST(REPLACE(SUBSTRING(INFO, 32, 48), CHAR(13), ») AS BIGINT) ELSE CAST(0 AS BIGINT) END) AS TOTALSIZE,
SUM(CASE WHEN INFO LIKE ‘TOTAL # OF FREE BYTES : %’ THEN CAST(REPLACE(SUBSTRING(INFO, 32, 48), CHAR(13), ») AS BIGINT) ELSE CAST(0 AS BIGINT) END) AS FREESPACE
INTO #DISKSPACE FROM (
SELECT DRIVE,
INFO
FROM #DRIVES
WHERE INFO LIKE ‘TOTAL # OF %’
GROUP BY DRIVE
ORDER BY DRIVE
Msg 8114, Level 16, State 5, Line 95
Error converting data type varchar to bigint.
Источник
Sql error converting varchar to bigint
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I am using one query in my Stored procedure when i am passing the values i am getting the error like Error converting data type varchar to bigint.
select @BasicPrice = convert(float, rate_dc) from RENAULT.TMFSCBaseValue
where PKConditionType_vc = ‘ZPRS’ and PKSalesDocType_vc = ‘YP’ and
PKDistributionChannel_vc = ’01’ and PKDivision_vc = ’91’
and PKServiceNo_vc = @ServiceNo and PKModelCode_vc = @ModelCode
and convert(bigint,@InvoiceDate) between convert(bigint,PKValidityStartDate_dt)
and convert(bigint,PKValidityEndDate_dt)
@DealerCode :: LN010391
@VehSrNo :: 9ZJ16246
@ModelCode :: LP11PB15RO11WD
@ServiceNo :: 1
@InvoiceDate :: 09/10/20
@ServiceDate :: 24/06/20
in table TMFSCBaseValue PKValidityStartDate_dt data type id varchar
Please help someone on this
Answers
Change the format of @ServiceDate :: 24/06/20
Currently, it is being passed in the format dd/mm/yy. Instead, make it as mm/dd/yy and you are done.
Hope, this helps !
-Vinay Pugalia
If a post answers your question, please click «Mark As Answer» on that post or «Vote as Helpful».
Web : Inkey Solutions
Blog : My Blog
Email : Vinay Pugalia
in table TMFSCBaseValue PKValidityStartDate_dt data type id varchar
What are the string format of the dates stored in these column and the data type of the @InvoiceDate parameter? Assuming the input parameters are varchar and the column values are in the same format, the query below should provide the desired results. Alternatively, you could cast as date instead of bigint.
Dan Guzman, SQL Server MVP, http://weblogs.sqlteam.com/dang/
Thanks for your reply.
Dates are stored in the format of 2010-10-06 in column invoice date
I tried above code still i am getting the error like Syntax error converting datetime from character string.
Change the format of @ServiceDate :: 24/06/20
Currently, it is being passed in the format dd/mm/yy. Instead, make it as mm/dd/yy and you are done.
Hope, this helps !
-Vinay Pugalia
If a post answers your question, please click «Mark As Answer» on that post or «Vote as Helpful».
Web : Inkey Solutions
Blog : My Blog
Email : Vinay Pugalia
Perhaps you have dates that are incorrectly formatted. Run the query below to see if this is the case:
Dan Guzman, SQL Server MVP, http://weblogs.sqlteam.com/dang/
If @InvoiceDate is a datetime, then that part is fine (otherwise it is not).
The problem is with the PKValidityStartDate and PKValidityEndDate, since you mention that these are varchar columns. If you convert this to bigint, then the value is assumed to be a number. So if you try that, you will get a conversion error.
Dan’s solution should fix that problem for you, because this first converts the varchar to a datetime. This will work, because you have stored dates in the column (not integer values). Then the value can be converted to bigint.
Having said that: this approach you are using to find out of a date is between a From and To date is nonstandard, not guaranteed to work the way you hope it will and will probably not have good performance. So I suggest you convert your varchar columns to datetime (or date) and change your query to something like this:
Источник
- Remove From My Forums
-
Вопрос
-
Hi,
I am a newbie user of MS SQL. I’m creating this procedure and been searching for the right solution to this problem for so long. I really need help this time! When I compile the procedure, it was fine but when I try to execute it like:
EXEC TA_COPY_TKT_DB 201166573491, 201166573491, ‘MSSQLSERVERDEV’, ‘MSSQLSERVERDEV’, ‘Demo84’, ‘Demo841’
I get this error:
Msg 8114, Level 16, State 5, Procedure TA_COPY_TKT_DB, Line 24
Error converting data type varchar to bigint.
Here’s the whole procedure I created:
ALTER PROCEDURE [dbo].[TA_COPY_TKT_DB]
@FromDocID
T_DOC_ID,@ToDocID
T_DOC_ID,@FromServerName
VARCHAR(50),@ToServerName
VARCHAR(50),@FromDatabaseName
VARCHAR(50),@ToDatabaseName
VARCHAR(50)as
begin
Declare
@SqlStmt
VARCHAR(150)Set Nocount On
/* Check PS_DOC_HDR if exists */
Begin Tran
EXEC USP_DEL_TKT @FromDocID
print @ToDocID
print @FromDocID
Set @SqlStmt = ‘INSERT INTO ‘ + @ToServerName + ‘.’ + @ToDatabaseName + ‘.dbo.PS_DOC_HDR ‘ +
‘SELECT * FROM ‘ + @FromServerName + ‘.’ + @FromDatabaseName + ‘.dbo.PS_DOC_HDR WHERE DOC_ID = ‘ + convert(bigint,@FromDocID)
Commit Tran
end
Ответы
-
Your last statement is of the form
Set @SqlStmt = <some concatened strings> + convert(bigint,@FromDocID)
But the result of convert(bigint, @FromDocID) is (of course) a bigint. So you have a string type and a bigint type. Bigint has a higher priority then varchar, so SQL will try to convert the concatened strings to a bigint, which it can’t do so you
get the error.So you must make the convert(bigint, @FromDocID) into a varchar (or char) type. Since you declared it as a T_DOC_ID datatype and didn’t tell us what T_DOC_ID really is, it’s hard to know exactly what you want. Some possibilities
If T_DOC_ID is an integer type (tiny int, smallint, int, bigint) then
Set @SqlStmt = <some concatened strings> + convert(varchar(20),@FromDocID)
If T_DOC_ID is something else then
Set @SqlStmt = <some concatened strings> + convert(varchar(20),convert(bigint, @FromDocID))
Tom
-
Помечено в качестве ответа
2 января 2012 г. 4:30
-
Помечено в качестве ответа
I have designed a SP where i need to update all the records for a table where ErrorId is not equal to the ones provided.In this stored procedure i am parsing and all the errorids delimited by ‘,’ into a varchar variable which i would be using for updating the table.On the second last line i get the error mentioned in the subject line.any help would be appreciated.
ALTER PROCEDURE [dbo].[sp_ParseAndUpdateDetails]
@NozzleID int,
@ParserString varchar(MAX)
AS
BEGIN
DECLARE @NextPos int
DECLARE @LoopCond tinyint
DECLARE @PreviousPos int
DECLARE @FlgFirst bit
DECLARE @QueryCondition varchar(MAX)
SET @LoopCond=1
SET @NextPos =0
SET @FlgFirst=0
SET @QueryCondition=»
WHILE (@LoopCond=1)
BEGIN
—Retrieving the Position of the delimiter
SET @NextPos =@NextPos + 1
SET @NextPos = CHARINDEX(‘,’,@ParserString, @NextPos)
—Retreiving the last substring
IF(@NextPos=0)
BEGIN
PRINT SUBSTRING(@ParserString,@PreviousPos + 1,(LEN(@ParserString)+1)- @PreviousPos)
SET @QueryCondition= @QueryCondition + ‘ AND ErrorId <> ‘ + CAST(SUBSTRING(@ParserString,@PreviousPos + 1,(LEN(@ParserString)+1)- @PreviousPos) AS bigint)
SET @PreviousPos = @NextPos
BREAK
END
—Retrieving the individual substrings
If @FlgFirst=0
—Retreiving the first substring
BEGIN
SET @FlgFirst=1
PRINT SUBSTRING(@ParserString,1, @NextPos—1)
SET @QueryCondition= @QueryCondition + CAST(SUBSTRING(@ParserString,1, @NextPos—1) AS bigint)
SET @PreviousPos = @NextPos
END
ELSE
—Retreiving the internmediate substrings
BEGIN
PRINT SUBSTRING(@ParserString,@PreviousPos + 1,(@NextPos—1)-@PreviousPos)
SET @QueryCondition= @QueryCondition + ‘ AND ErrorId <> ‘ + CAST(SUBSTRING(@ParserString,@PreviousPos + 1,(@NextPos—1)-@PreviousPos) AS bigint)
SET @PreviousPos = @NextPos
END
END
print ‘ErrorId <>’ + @QueryCondition
UPDATE [ESMS2_DBMS].[dbo].[ErrorDetails]
SET ErrorRectifyDateTime=GETDATE()
WHERE (NozzleId = @NozzleId) AND (ErrorRectifyDateTime IS NULL) AND (ErrorId <> @QueryCondition)
END
February 25, 2016 at 12:03 pm
#308419
I am working on a project where I need to move values from one table (tableOriginal) into another table (tableNew). The original table has two columns EstCards / EstAccts that are stored as varchar but in the new table, we want these values stored as integer (technically bigint because some values in the original table for some reason are in the billions).
When I do the following SQL Statement (see pasted below), I am getting an error saying (this will be added to the SELECT INTO statement but for now just need to convert the varchar values to bigint and if they cannot be converted, enter zero in the new table):
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to bigint.
I am not sure what record this is breaking on to know what I am missing. Do you know of a way to check if a varchar can be converted to a number and if it cannot, I want to insert a zero or even know how to find the record that is failing the test? I really only think I need only one “WHEN” statement, but I am trying anything I can think of.
SELECT
PID
, IDate
, BegDate
, EndDate
, CASE
WHEN EstCards IS NULL THEN 0
WHEN LEN(EstCards) = 0 THEN 0
WHEN ISNUMERIC(EstCards) = 0 THEN 0
WHEN ISNUMERIC(EstCards) = 1 THEN CAST(EstCards AS BIGINT)
ELSE 0
END
, CASE
WHEN EstAccounts IS NULL THEN 0
WHEN LEN(EstAccounts) = 0 THEN 0
WHEN ISNUMERIC(EstAccounts) = 0 THEN 0
WHEN ISNUMERIC(EstAccounts) = 1 THEN CAST(EstAccounts AS BIGINT)
ELSE 0
END
, 0
, 0
, ‘Data Migration’
, ‘svc’
, GETDATE()
FROM
tableOriginal
Any help is appreciated
dogramone
Hall of Fame
Points: 3216
kocheese
SSCommitted
Points: 1517
Appreciate the help, but I do not have access to create database objects. We «own the data, but not the objects / database», so if possible, I need to be able to do this with built in T-SQL.
Luis Cazares
SSC Guru
Points: 183694
No need for a performance problem caused by a scalar udf. There’s a simple formula explained in the following article that can help you simplify your code.
http://www.sqlservercentral.com/articles/ISNUMERIC()/71512/
SELECT
PID
, IDate
, BegDate
, EndDate
, CASE
WHEN EstCards NOT LIKE '%[^0-9]%' THEN CAST(EstCards AS BIGINT)
ELSE 0
END
, CASE
WHEN EstAccounts NOT LIKE '%[^0-9]%' THEN CAST(EstAccounts AS BIGINT)
ELSE 0
END
, 0
, 0
, 'Data Migration'
, 'svc'
, GETDATE()
FROM
tableOriginal;
Note: This won’t handle negative values. You’ll need to modify the condition to handle negative values correctly.
Luis C.
General Disclaimer:
Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?
How to post data/code on a forum to get the best help: Option 1 / Option 2
SQLBill
SSC Guru
Points: 51440
You should also be able to use ISNUMERIC to see what data is not numeric and therefore can’t be converted.
-SQLBill
Luis Cazares
SSC Guru
Points: 183694
If by any chance you’re working with SQL Server 2012 or later, you can use TRY_CAST or TRY_CONVERT.
That wasn’t my first suggestion because this is the 2008 forum, so it might not apply to you.
Luis C.
General Disclaimer:
Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?
How to post data/code on a forum to get the best help: Option 1 / Option 2
Jeff Moden
SSC Guru
Points: 1002244
Luis Cazares (2/25/2016)
If by any chance you’re working with SQL Server 2012 or later, you can use TRY_CAST or TRY_CONVERT.
Have you compared it for performance?
Luis Cazares
SSC Guru
Points: 183694
Jeff Moden (2/25/2016)
Luis Cazares (2/25/2016)
If by any chance you’re working with SQL Server 2012 or later, you can use TRY_CAST or TRY_CONVERT.
Have you compared it for performance?
I hadn’t test it for performance myself, but I just did. The use of TRY_CAST or TRY_CONVERT uses minimal resources and is almost as fast as not converting the data at all. Using the CASE statement is about 5 times slower than using just functions.
Here’s the quick test that I made. I changed the amount of invalid values but didn’t impact the performance.
WITH
E(n) AS(
SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)
),
E2(n) AS(
SELECT a.n FROM E a, E b
),
E4(n) AS(
SELECT a.n FROM E2 a, E2 b
),
cteTally(n) AS(
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) n
FROM E4 a, E2 b
)
SELECT CAST( n AS varchar(7))
+ CASE WHEN n < 100000 THEN 'a' ELSE '' END --adding some invalid conversions
AS nString
INTO #Test
FROM cteTally;
DECLARE @nString varchar(7),
@nBigInt bigint;
SET STATISTICS TIME ON;
PRINT 'Dry run';
SELECT @nString = nString
FROM #Test;
PRINT 'Using TRY_CONVERT';
SELECT @nBigInt = ISNULL( TRY_CONVERT( bigint, nString), 0)
FROM #Test;
PRINT 'Using CASE';
SELECT @nBigInt = CASE WHEN nString NOT LIKE '%[^0-9]%' THEN CAST(nString AS BIGINT)
ELSE 0
END
FROM #Test;
SET STATISTICS TIME OFF;
GO
DROP TABLE #Test;
I remember that you mentioned a similar issue when formatting dates using CASE instead of native functions.
Luis C.
General Disclaimer:
Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?
How to post data/code on a forum to get the best help: Option 1 / Option 2
Jeff Moden
SSC Guru
Points: 1002244
Jeff Moden
SSC Guru
Points: 1002244
SQLBill (2/25/2016)
You should also be able to use ISNUMERIC to see what data is not numeric and therefore can’t be converted.
-SQLBill
Careful now. ISNUMERIC should never be confused with ISALLDIGITS. It will allow a great many things that, for example, will translate to a MONEY datatype but not to an INT. Please see the following article for 1 of the alternatives…
http://www.sqlservercentral.com/articles/ISNUMERIC()/71512/
Jeff Moden
SSC Guru
Points: 1002244
Luis Cazares (2/27/2016)
Jeff Moden (2/25/2016)
Luis Cazares (2/25/2016)
If by any chance you’re working with SQL Server 2012 or later, you can use TRY_CAST or TRY_CONVERT.
Have you compared it for performance?
I hadn’t test it for performance myself, but I just did. The use of TRY_CAST or TRY_CONVERT uses minimal resources and is almost as fast as not converting the data at all. Using the CASE statement is about 5 times slower than using just functions.
Here’s the quick test that I made. I changed the amount of invalid values but didn’t impact the performance.
WITH
E(n) AS(
SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)
),
E2(n) AS(
SELECT a.n FROM E a, E b
),
E4(n) AS(
SELECT a.n FROM E2 a, E2 b
),
cteTally(n) AS(
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) n
FROM E4 a, E2 b
)
SELECT CAST( n AS varchar(7))
+ CASE WHEN n < 100000 THEN 'a' ELSE '' END --adding some invalid conversions
AS nString
INTO #Test
FROM cteTally;
DECLARE @nString varchar(7),
@nBigInt bigint;
SET STATISTICS TIME ON;
PRINT 'Dry run';
SELECT @nString = nString
FROM #Test;
PRINT 'Using TRY_CONVERT';
SELECT @nBigInt = ISNULL( TRY_CONVERT( bigint, nString), 0)
FROM #Test;
PRINT 'Using CASE';
SELECT @nBigInt = CASE WHEN nString NOT LIKE '%[^0-9]%' THEN CAST(nString AS BIGINT)
ELSE 0
END
FROM #Test;
SET STATISTICS TIME OFF;
GO
DROP TABLE #Test;
I remember that you mentioned a similar issue when formatting dates using CASE instead of native functions.
Very cool. I’ll try this Monday when I get to work. Thank you, Sir.
Considering the miserable performance of the new FORMAT function, I’m suspicious of anything new anymore. I really appreciate you putting this together. Thanks.
Hugo Kornelis
SSC Guru
Points: 64770
I’m a bit late to the party, but depending on what version of SQL Server you are on, have you looked at using TRY_CAST insterad of trying to build it yourself with that clunky CASE expression?
EDIT: Oops, never mind. Now I see that someone else already posted that suggestion. My bad.
Ed Wagner
SSC Guru
Points: 287023
Well, until this thread, I’d never considered racing my NumbersOnly ITVF against the new TRY_CONVERT function. We’re just migrating one instance to SQL 2012 and it had never occurred to me. Now, however, I have something new to try. They don’t have identical functionality, but are similar enough that the curiosity is killing me.
I honestly hope TRY_CONVERT performs well. Thank you, Luis, for you post causing me me to think of it.