SQL Code:
DECLARE #SortOrder nvarchar(max);
SET #SortOrder = 'name';
SELECT * FROM [database_name].[schema_name].[table_name]
ORDER BY CASE #SortOrder
WHEN 'id' THEN id
WHEN 'name' THEN name
END;
Output:
Msg 245, Level 16, State 1, Line 3
Conversion failed when converting the nvarchar value 'foo' to data type int.
When I instead put #SortOrder = 'id', it works flawlessly. When I do a normal SELECT and ORDER BY name, it also works flawlessly.
Why would it try to convert that nvarchar value to data type int, and how can I stop it from doing so?
CASE is an expression that returns a single value of a specific data type. The potential values must be compatible, and since you must have a name value of foo, which can't be converted to INT, you get this error. The easiest way to solve this problem is to separate your ORDER BY expressions by data type:
ORDER BY CASE #SortOrder WHEN 'id' THEN id END,
CASE #SortOrder WHEN 'name' THEN name END;
Another alternative (which may be better for plan caching as long as you have optimize for ad hoc workloads on) would be dynamic SQL:
DECLARE #sql NVARCHAR(MAX) = N'SELECT ... ORDER BY ' + QUOTENAME(#SortOrder) + ';';
EXEC sp_executesql #sql;
Also not sure why you would give your #SortOrder a max data type - no column name could ever be anywhere near that large.
All routes through a case statement must output the same data type. Try casting the ID to a string like this and it will work.
DECLARE #SortOrder nvarchar(max);
SET #SortOrder = 'name';
SELECT * FROM [database_name].[schema_name].[table_name]
ORDER BY CASE #SortOrder
WHEN 'id' THEN cast(id AS NVARCHAR(20))
WHEN 'name' THEN name
END;
Related
My table has column names m1,m2,m3...,m12.
I'm using iterator to select them and insert them one by one in another table.
In this iterator I'm trying to generate filed names with:
'['+concat('m',cast(#P_MONTH as nvarchar))+']'
where #P_MONTH is incrementing in each loop.
so for #P_MONTH = 1 this suppose to give [m1] which works fine.
But when I run query I get:
Conversion failed when converting the nvarchar value '[m1]' to data
type int.
And if I put simply [m1] in that select it works ok.
How to concat filed name so it can be actually interpreted as filed name from certain table?
EDIT
Here is full query:
DECLARE #SQLString nvarchar(500),
#P_YEAR int,
#P_MONTH int = 1
set #P_YEAR = 2018
WHILE #P_MONTH < 13
BEGIN
SET #SQLString =
'INSERT INTO [dbo].[MASTER_TABLE]
(sector,serial,
date, number, source)'+
'SELECT ' + '[SECTOR],[DEPARTMENT]' +
QUOTENAME(cast(CONVERT(datetime,CONVERT(VARCHAR(4),#P_YEAR)+RIGHT('0'+CONVERT(VARCHAR(2),#P_MONTH),2)+'01',5) as nvarchar))+
QUOTENAME ('M',cast(#P_MONTH as nvarchar)) +
'EMPLOYED' +
'FROM [dbo].[STATS]'+
'where YEAR= #P_YEAR'
EXECUTE sp_executesql #SQLString
SET #P_MONTH = #P_MONTH + 1
END
It's still not working. It executes successfully but it does nothing.
Good day,
Let's create a simple table for the sake of the explanation
DROP TABLE IF EXISTS T
GO
CREATE TABLE T(a1 INT)
GO
INSERT T(a1) VALUES (1),(2)
GO
SELECT a1 FROM T
GO
When we are using a query like bellow, the server parse the text as a value and not as a column name
DECLARE #String NVARCHAR(10)
SELECT #String = '1'
--
SELECT '['+concat('a',cast(#String as nvarchar))+']'
FROM T
GO
This mean that the result will be 2 rows with no name for the column and the value will be "[a1]"
Moreover, the above query uses the brackets as part of the string.
One simple solution is to use the function QUOTENAME in order to add brackets around a name.
Another issue in this approach is the optional risk of SQL Injection. QUOTENAME might not be perfect solution but can help in this as well.
If we need to use entities name dynamically like in this case the column name then for most cases using dynamic query is the best solution. This mean to use the Stored Procedure sp_executesql as bellow
DECLARE #String INT
SELECT #String = 1
DECLARE #SQLString nvarchar(500);
SET #SQLString =
'SELECT ' + QUOTENAME(concat('a',cast(#String as nvarchar))) + ' FROM T'
EXECUTE sp_executesql #SQLString
GO
Hi I am trying to do the following:
SELECT #IDENTITY_COLUMN = (
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'tbltest1'
SELECT #LAST_VALUE_USED = (
SELECT ISNULL(MAX(#IDENTITY_COLUMN),0)
FROM tbltest1
)
If there are no rows, it works fine but when there is a row, the second query is returning a string that has the column name and I believe it is because #IDENTITY_COLUMNhas quotes in it. Hence I am getting Conversion failed when converting the nvarchar value 'columnname' to data type int. How can I solve this problem?
Help appreciated!
I think you're trying to get the maximum value of an IDENTITY column from a table if such a column exists. You'd need dynamic SQL for that. Something like:
DECLARE #identity_column sysname;
DECLARE #query nvarchar(MAX);
SET #identity_column = (SELECT column_name
FROM information_schema.columns
WHERE table_name = 'tbltest1');
IF #identity_column IS NOT NULL
BEGIN
SET #query = '
SELECT isnull(max(' + quotename(#identity_column) + '), 0)
FROM tbltest1;
';
EXECUTE (#query);
END;
Note:
For object names use sysname, that's an extra type for them. Don't use varchar or navarchar etc..
Always use quotename() if embedding object names in a dynamic query. That'll prevent funny things from happen, if the object name contains non alpha numeric characters or is odd in other ways.
I have SQL code that I am running and am getting an error when I pass in certain information.
select * from OBX.BTOCUST
--where [CUSTID] like 'sci'
--order by BRANDING desc
where BRANDING not like '0x4767374ADABABBAB9B96865669F9D9DE4E3E3838182ACABAB9E9D9DE3E3E3848182231F20000000FFFFFFFFFFFF00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000021F90401000026002C000000000D023C000006FF409370482C1A8FC8A472C96C3A9FD0A8744AAD5AAFD8AC76CBED7ABFE0B0784C2E9BCFE8B47ACD6EBBDFF0B87C4EAFDBEFF8BC7ECFEFFBFF8081828384858687884A0D03238D8E8F9091928E1520178998999A9B9C61148F1403A2A3A4A5A68CA1A49F941A9DAEAFB0B19A0C8C8D031925B9BABBBCBDB9231BBD17138F0CB2C7C8C9CA710C8D1505BED1D225CD1DD21AAB13CBDBDCDDDE57C4230CD3BC171916161ABD1613E40CE1DFF1F2F3F18D13E3E4BF8FE8C41B161C8D2EE42BF18982317A08132AD4147060090C8E0658CB550092C38A231A2CDCC8B1239F108D1C426C84A1D7C8900E378CA0E0B1A5CB976C2A8C2839F051B40EAB1CEA83C9B3A7CFFF2D204708CC77C166340FC07496687444410005044C18C882202A9600010008D17A27C0D49F607F3698E910A92369D59432024184C001AB041670B5F28044042B0B489018428084803912B826207120AC619E1039A434EA6B98D212163212A94BC4C0DC2A042024C0AC570291057FE590982B40C1E1D32D19411B98E19187C7D32A6A1C2280F083219B8538BD6D820080DF261064FDCDF5B76500B98560B52A4438F32100F44230325D7780E4267E47BD9E1D000103DC8960259200387821049C561592E0008907067C0367FF60BD89F200A6064080BA7F32D50E7500092EB0F922DB647A91C01F797209C05F667A99A0575D119AA0800006E4151A01A54170FF406E0840A0C0874540306112092C306268128E2601612D3E901709D5C58580020E14A797027A6DE600027915D6A25E0140B89709260610819000B827416D47FA27E52B003A140981BC4C32823407F23523090E9826D501A60DA6557424BCB8978942F66642007E09915776605A4842543012E1805E975546A6092F5AD5D99E85E9B50001115438A78424B6E8C09E0920E0806F15B6A8E391242CD09B82424089E67353868A4995034536A02F66356201395D1281807B9D59FA1B8C685E566175708656A183B2562A44827D0E5161749AB61800117C6E4AC2541526F86B94161E60008F51264BE75E2F1E6B426DA6D576ACB5A2868B08A9039DE40896BA68C0FF18979219E156827D9180D5BCD716C127A2CAC5D9A2BDF2D2FB995E0B1A316CB3A3215BB0A5FB0EF9AC1119566A2D9ADBCADBA9C4DE222CEEC585905BEE95BC9C54413EAD6E8B5DA26806BC95AFC1193A44AE0B1BFC15C37A3980C4C0325BFC2C577A318B29C195D108F1CD27AF2971C4FC550C2EC648FFA1713EEF70ACCB2A23BC960BBABB842C008BD915E6DEA44278F6335F4EAEACAFB578DA859E116A5E96C06D7BEA4623D0C2161C6FCB31B73CF1ACD51E0C310243E73595D107272D381F4B0F148E96E71600113EBD58ED80009BBD4A5B82DA52889D54770D9128D77CEB45A2017B122666110F380900021124A724010EB47962DC0200505BB123C697FF267ABECE48AD5C48D669028542EC09009C51B16EF6EB83278F47E14C1F7E6E073249C2EE6CCAF9F6A4042F9B108100D581E72F1197CDBBA0015733C72186491080C0D559952880572B63F5329FEB3FC01CF9B10F215CFB42907FDB855CE19067BCA72D023C807B0BDA5F56E6953DE539300ECC2347AA1EA198622C0525066AD7318EF6C00E2A248225D8C0C77821204904C328C4186106A9270B0E7AF085F20061D4CA01354850E08228890C4D56980CE4C1F087DF90E144A6060A8C48628491615CE33408C4263A510C32DCC505A046810B18311234F1C00062C3C4277AF18B58882052B6A80F5BE4425D93D049C8C0C8C6363E2182E138E3238672920906FFE3224C24CE6F2E0707F56DE1387C74A320953682D5F402205ACA45334882C8460C11645DFCDA12B425866269EF3D5B60D920370908E6A9441D68DC870756010DE729658D924C1F25C310A50440005456D0242767B907E68DA01DB9A8E12330B01A8BA83192283B425C56F905BE854196B44CA61D4048114890314B8EB8E12F59582F2138094A034C509C52149D0799285366A350E8C4149711DDE9597C6AD2D00EA0A20384E69BAFCA5366DA79A87C614D99F8846021F3D1C846480D9A24392530A3E42967454C5B06F8D3C0C099B99CD5A55810B80B9C3C53CD834A8504A609D4B52230B7DE49F4766FD2573E47FA066696A09F235047C72C38CD227C0D70FF47AA58AF8E94CA08FD2C009A7A51685E2AAF8E12AB9A1582534EF5854C921A350D26BDE23E7911BDA408949A3CFDD6AE8646247FD5742F920480868236B9AC2C14A8D0DAD656437ACFA39A950C2625C82354AA0B5339F231A8AC144C27A62D80B9146536AD108F84A3AFA81A806660D58D7BC86ACFB31AB60C6955892356B58BA66E09AE03EDAAC22C6A82AD3DE7AAF57A17612B5AB1B6D9693A3FAB10AC365BD4C39A960B696D8D237658C64628913591A5EB646B2301DFC0295317E2AAC1EA8526058CF553B2E59156E03495D0EEEC4E632DED69977B85B1B0761AAAC5E02944A19611B0257EE27B13568627BFE6684673F993CAF7B4BB407A012002FC09FD0004BEE2BFE0581502EFFBCABCCACB9FF3668E7BD9192F73F75B0575A9301FEBBA86950AC9DF021F4626CF95C614CF350D0A28A6262330B084C13216690EA4288B8DC63F02C494097B98270DD1497457C2810258600314C0C06BAFD188063000040DF8C08767CC1167AC18BA8A7D4405FE3990823020C51FA88036684C647A8CE5960542073A86A293458280011F10C5073650E42ACB63911430648174820D7B984023231800950B60E53277E370CFDC3224ED610C306B200426B88499E7BC0C5D4EF7CE781605242AD08A215440232AA1B3A0930165E721EED087967111821C66390FFAD1908EB4A4274DE94A5BFAD298CEB4A637CDE94E7B5A994100003B'
When I uncomment the --where [CUSTID] like 'sci' and comment out branding the query runs and am able to see results. But when I run where branding I get an error:
Msg 8116, Level 16, State 1, Line 1
Argument data type varchar is invalid for argument 2 of like function.
also another thing is when i uncomment the order by BRANDING desc it gives me another error.
that error is
Msg 306, Level 16, State 2, Line 3 The text, ntext, and image data
types cannot be compared or sorted, except when using IS NULL or LIKE
operator.
What do I need to do to get the command to actually work?
This error message is what you get if BRANDING is of type IMAGE, which is incomparable (as in, literally, it cannot be compared in any way, not even to another IMAGE). To overcome the limitations of this type, SQL Server 2005 introduced the VARBINARY(MAX) type, which has the same purpose but isn't burdened with the special case handling that IMAGE requires (likewise, (N)VARCHAR(MAX) was introduced to replace (N)TEXT). IMAGE should not be used for new work; VARBINARY(MAX) is superior in all respects. If existing IMAGE columns can be changed to VARBINARY(MAX), do so.
If that isn't possible, the IMAGE can still be converted on the fly. In the query above:
select * from OBX.BTOCUST
where CONVERT(VARBINARY(MAX), BRANDING) <> 0x476737.....00003B
Here the 0x476737.... is a BINARY literal. To convert a hexstring to a binary, use CONVERT(VARBINARY(MAX), #string, 1) (with leading "0x") or CONVERT(VARBINARY(MAX), #string, 2) (without leading "0x").
Convert your image or text or ntext column data type to varbinary(max), varchar(max) or nvarchar(max).
The image, text, and ntext data types are deprecated and will be removed in a future version of SQL Server. They are very difficult and awkward to work with. The varchar(max) and nvarchar(max) have all the benefits of nearly unlimited string size, and none of the drawbacks of text or ntext. They also work with all the normal string functions you'd expect.
This is a quick and dirty way of doing it that I just put together, but keep in mind what you are asking of your server in the absence of fulltext. It ignores the data type mismatches as low level errors in your message output. You can check the message output for a rudimentary sort of progress on it as it is running.
Declare #SearchString nvarchar(50) = 'SEARCH STRING HERE'
Declare #TableList Table (TableName nvarchar(128))
Declare #Table nvarchar(128)
Declare #ColumnList Table (ColumnName nvarchar(128))
Declare #Column nvarchar(128)
Declare #Results Table (TableName nvarchar(128), ColumnName nvarchar(128), String nvarchar(max))
Declare #cmd nvarchar(max)
Insert Into #TableList
Select TABLE_NAME From INFORMATION_SCHEMA.Tables Where Table_Type = 'BASE TABLE'
While Exists (Select 1 From #TableList)
Begin
Set #Table = (Select Top 1 TableName From #TableList)
Print 'Searching '+#Table+'...'
Insert Into #ColumnList
Select Column_Name From INFORMATION_SCHEMA.Columns Where Table_Name = #Table
While Exists (Select 1 From #ColumnList)
Begin
Set #Column = (Select Top 1 ColumnName From #ColumnList)
Print 'Searching ' +#Table + '.' + #Column+'...'
Set #cmd = 'Select '''+#Table+''', '''+#Column+''', '+#Column+' From '+#Table+' Where '+#Column+' Like ''%'+#SearchString+'%'''
--Select #cmd
Insert Into #Results
Exec (#cmd)
Delete From #ColumnList Where ColumnName = #Column
End
Delete From #TableList Where TableName = #Table
End
Select * From #Results
I created the procedure listed below:
CREATE procedure getdata
(
#ID int,
#frm varchar(250),
#to varchar(250)
)
AS
BEGIN
DECLARE #SQL nvarchar(500)
set #SQL = 'select'
set #SQL = #SQL + ' EmpName, Address, Salary from Emp_Tb where 1=1 '
IF (#ID <> '' and #ID is not null)
Begin
SET #sql=#sql+' AND Emp_Id_Pk=' +#ID
End
END
print #sql
--execute (#sql)
I try to execute it using:
**execute getdata 3,'','';**
But I'm getting the following error:
Conversion failed when converting the nvarchar value 'select EmpName,
Address, Salary from Emp_Tb where 1=1 AND Emp_Id_Pk=' to data type int
Please help.
You are trying to concatenate a string and an integer.
You need to cast #ID as a string.
try:
SET #sql=#sql+' AND Emp_Id_Pk=' + CAST(#ID AS NVARCHAR(10))
Try Using
CONVERT(nvarchar(10),#ID)
This is similar to cast but is less expensive(in terms of time consumed)
I was using a KEY word for one of my columns and I solved it with brackets []
I use the latest version of SSMS or sql server management studio. I have a SQL script (in query editor) which has about 100 lines of code. This is error I got in the query:
Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the nvarchar value 'abcd' to data type int.
Solution - I had seen this kind of error before when I forgot to enclose a number (in varchar column) in single quotes.
As an aside, the error message is misleading. The actual error on line number 70 in the query editor and not line 2 as the error says!
don't use string concatenation to produce sql, you can use sp_executesql system stored prcedure to execute sql statement with parameters
create procedure getdata #ID int, #frm varchar(250), #to varchar(250) as
begin
declare #sql nvarchar(max), #paramDefs nvarchar(max);
set nocount on;
set #sql = N'select EmpName, Address, Salary from Emp_Tb where #id is null or Emp_Id_Pk = #id';
set #paramDefs = N'#id int';
execute sp_executesql #sql, #paramDefs, #id = #ID;
end
see sp_executesql
I got this error when I used a where clause which looked at a nvarchar field but didn't use single quotes.
My invalid SQL query looked like this:
SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = 13028533)
This didn't work since the Number column had the data type nvarchar. It wasn't an int as I first thought.
I changed it to:
SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = '13028533')
And it worked.
You got this Error because you tried to convert column DataType from String to int which is
leagal if and only if
you dont have row in that table with string content inside that column
so just make sure your previously inserted Rows is compatible with the new changes
I have faced to the same problem, i deleted the constraint for the column in question and it worked for me. You can check the folder Constraints.
Capture :
You must use CONCAT and not the +
SET #sql = CONCAT(#sql,' AND Emp_Id_Pk=' ,#ID )
I am getting the error 'Error converting data type nvarchar to float' when running the following
declare
#completeCommand nvarchar (max) = 'x'
,#paramVal nvarchar (100)
,#paramName nvarchar (100)
,#paramType nvarchar (100)
,#tempParam sql_variant
declare #parameterList table (
RowID int identity (1,1)
,ParameterValue nvarchar (100)
,ParameterName nvarchar (100)
,ParameterType nvarchar (100)
)
insert into #parameterList
values
('10', 'Param1', 'int')
,('test', 'Param2', 'nvarchar')
-- Process each parameter one at a time
declare ParameterCursor cursor fast_forward for
select ParameterValue, ParameterName, ParameterType
from #parameterList
order by RowID
open ParameterCursor
fetch next from ParameterCursor into #paramVal, #paramName, #paramType
if ##FETCH_STATUS = 0
set #completeCommand = #completeCommand + ' '
while ##FETCH_STATUS = 0
begin
print #completeCommand
-- verify the datatype is correct
set #tempParam = case #paramType
when 'int' then CAST (#paramVal as int)
when 'float' then CAST (#paramVal as float)
when 'nvarchar' then CAST (#paramVal as nvarchar)
else 'NULL'
end
set #completeCommand = #completeCommand + #paramName + ' = ' + #paramVal + ','
fetch next from ParameterCursor into #paramVal, #paramName, #paramType
end
close ParameterCurosr
deallocate ParameterCursor
What I am trying to do is verify that user entered data matches the expected data type before the data is added to a command string. Any feedback on why the above code fails would be greatly appreciated.
Cheers,
Joe
The issue is that CASE will return the data type with the highest precidence, of which is float for this statement. see CASE (Transact-SQL) and Data Type Precedence (Transact-SQL).
To get this CASE to work add a bogus WHEN 'xzy' then CAST (#paramVal as sql_variant) which will cause CASE to use sql_variant as the return data type.
OR remove the CASE and use IF-ELSE, like:
IF #paramType='int'
set #tempParam = CAST (#paramVal as int)
ELSE IF #paramType='float'
set #tempParam = CAST (#paramVal as float)
ELSE IF #paramType='nvarchar'
set #tempParam = CAST (#paramVal as nvarchar)
ELSE
set #tempParam = NULL
What you used was Simple Case function. Searched Case function should work (see below).
I've just tried it in a very simple query:
DECLARE #type VARCHAR(100)
DECLARE #input VARCHAR(100)
DECLARE #value SQL_VARIANT
SET #type = 'varchar'
SET #input = 'test'
SET #value = CASE
WHEN #type = 'varchar' THEN #input
WHEN #type = 'int' THEN CAST(#input AS VARCHAR)
END
On SQL Server 2005 I am getting the same error, but the following is from SQL Server 2008 doc:
Simple CASE function:
Evaluates input_expression, and then in the order specified, evaluates input_expression = when_expression for each WHEN clause.
Returns the result_expression of the first input_expression = when_expression that evaluates to TRUE.
If no input_expression = when_expression evaluates to TRUE, the SQL Server 2005 Database Engine returns the else_result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.
Searched CASE function:
Evaluates, in the order specified, Boolean_expression for each WHEN clause.
Returns result_expression of the first Boolean_expression that evaluates to TRUE.
If no Boolean_expression evaluates to TRUE, the Database Engine returns the else_result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.
If this is true, then Simple Case will do all the CASTS and then decide qhich one to use, while Searched Case will evaluate the boolean expression and then decide which CAST to execute. This should be the solution.
Otherwise, you can probably use IF ... THEN ... ELSE, as proposed in another answer.