Select query an int or nvarchar value - sql

I'm trying to create a search function that is able to search by condition, platenumber and maximum volume using a select statement:
select Condition, PlateNumber, MaximumVolumeLoad
from [Truck Table]
where Condition=#id OR PlateNumber=#id OR MaximumVolumeLoad>=#id
However, the problem is My MaximumVolumeLoad column is set into int and whenever I search for the condition, I get this error:
Conversion failed when converting the nvarchar value 'good' to data type int.
Is there any way where I can search for them at the same time without having to create another query?

This seems like a bad idea, but you can do it by converting the value to a number:
select Condition, PlateNumber, MaximumVolumeLoad
from [Truck Table] tt
where Condition = #id or
PlateNumber = #id or
MaximumVolumeLoad >= try_convert(int, #id);
Note that if the value is not a valid integer, this will return NULL, so it will never match MaximumVolumeLoad. Presumably, this is the correct behavior.

May be an alternative to what has been suggested by Gordon is to convert the column to varchar before the compare. This should behave in the same way.
select Condition, PlateNumber, MaximumVolumeLoad
from [Truck Table] tt
where Condition = #id or
PlateNumber = #id or
cast(MaximumVolumeLoad as varchar(10)) >= #id;
Note: Forgot to add that it assumes that you will have alphabets in the #id. Based on ASCII character set numbers come before alphabets. So this should work as expected if it is any string that is entered.
But is you check for '2' >= '+' the results could go wrong. (if #id has a value of a '+')

Related

SQL Server WHERE clause : column IS NULL or column = parameter value

The code snippet below is what I'm trying to achieve, but I'm having trouble making it work. If the parameter that gets passed into the procedure is null, I want to only return the rows with a WHERE clause IS NULL, but if there is a value, I want to return the rows that are equal to the value passed in. Dynamic SQL seems like it would work, but I'm curious if there's an easier way I'm missing. Thanks in advance.
PARAM:
#id varchar(10) = '123456789'
SELECT *
FROM TABLE T
WHERE
CASE
WHEN #id IS NULL THEN (id IS NULL)
ELSE id = #id
END
The logic you want is:
WHERE (#id IS NULL AND id IS NULL) OR
id = #id
You're trying to use a CASE expression like a Case (Switch) statement. Switches don't exist in T-SQL, and a CASE expression returns a scalar value not a boolean result.
Don't, however, use CASE expressions in the WHERE, use proper Boolean logic:
SELECT *
FROM YourTable YT
WHERE (ID = #ID
OR (ID IS NULL AND #ID IS NULL))

using parameters with max len and check for null vall

I'm trying to get a count for a column to see the max characters. I'm getting a warning, I know it doesn't effect, but it's more of an annoyance and would like to eliminate the warning.
My example is as follows:
Declare #Countthis varchar (255)
select #Counthis = max(len(col1)) from #temp
Print '------- This is the largest count for this column-----' + #Countthis
The warning I receive is:
Warning: Null value is eliminated by an aggregate or other SET operation.
I tried using Case statement but I couldn't figure it out. If the value is NULL just ignore the value.
Is this possible?
You can use
Declare #Countthis varchar (255)
select #Counthis = max(len(IsNull(col1,''))) from #temp

SQL Server : Nvarchar to Varchar

I have a table with two columns, one is of type Varchar and the other in NVarchar.
I want to update all the rows so VarcharField = NVarcharField.
It won't let me because some of the rows contain chars that are not allowed in varchar column with the current code page.
How can I find these rows?
Is it possible to remove any char that doesn't fit the specific code page I'm using?
SQL Server 2012.
You can find the rows by attempting to convert the nvarchar() col to varchar():
select nvarcharcol
from t
where try_convert(varchar(max), nvarcharcol) is null;
Try this..
to find the rows with values that are not supported by varchar
declare #strText nvarchar(max)
set #strText = 'Keep calm and say தமிழன்டா'
select cast(#strText as varchar(max)) col1 , N'Keep calm and say தமிழன்டா' col2
Here #strText has non-english chars, When you try to cast that into varchar the non-english chars turns into ????. So the col1 and col2 are not equal.
select nvar_col
from tabl_name
where nvar_col != cast(nvar_col as varchar(max))
Is it possible to remove any char that doesn't fit the specific code page I'm using?
update tabl_name
set nvar_col = replace(cast(nvar_col as varchar(max)),'?','')
where nvar_col != cast(nvar_col as varchar(max))
Replace ? with empty string and update them.
If Gordon's approach doesn't work because you get question marks from TRY_CONVERT instead of the expected NULL, try this approach:
SELECT IsConvertible = CASE WHEN NULLIF(REPLACE(TRY_CONVERT(varchar(max), N'人物'), '?',''), '') IS NULL
THEN 'No' ELSE 'Yes' END
If you need it as filter for the rows that can't be converted:
SELECT t.*
FROM dbo.TableName t
WHERE NULLIF(REPLACE(TRY_CONVERT(varchar(max), t.NVarcharField), '?',''), '') IS NULL

SQL Server compare varchar field with binary(16)

I have 2 tables - Table A with primary key column of type binary(16) and another table B with foreign key referring to the same column but with data type as varchar(50). So table A has values like 0x0007914BFFEC4603A6900045492EFA1A and table B has the same value stored as 0007914BFFEC4603A6900045492EFA1A.
How do i compare these 2 columns, which would give me
0007914BFFEC4603A6900045492EFA1A = 0x0007914BFFEC4603A6900045492EFA1A
You will need to convert the binary(16) to a string. A sample of how to do this can be found in the question below. This question converts a varbinary to a string, but the same technique can be used for a binary column or variable:
SQL Server converting varbinary to string
Example code for how to do this is below:
declare #bin binary(16), #str varchar(50)
set #bin = 0x0007914BFFEC4603A6900045492EFA1A
set #str = '0007914BFFEC4603A6900045492EFA1A'
select #bin as'binary(16)', #str as 'varchar(50)'
-- the binary value is not equal to the string value
-- this statement returns 'binary value is not equal to string'
if #bin = #str select 'binary value is equal to string'
else select 'binary value is not equal to string'
declare #binstr varchar(50)
select #binstr = convert(varchar(50), #bin, 2)
select #binstr
-- the converted string value matches the other string
-- the result of this statement is "converted string is equal"
if #binstr = #str select 'converted string is equal'
else select 'converted string is NOT equal'
To use this in a join, you can include the conversion in the ON clause of the inner join or in a WHERE clause:
select *
from TableA
inner join TableB
on TableB.char_fk = convert(varchar(50), TableA.bin_pk, 2)
UPDATE
For SQL Server 2005, you can use an XML approach shown by Peter Larsson here:
-- Prepare value
DECLARE #bin VARBINARY(MAX)
SET #bin = 0x5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8
-- Display the results
SELECT #bin AS OriginalValue,
CAST('' AS XML).value('xs:hexBinary(sql:variable("#bin"))', 'VARCHAR(MAX)') AS ConvertedString
You can also use the undocumented function sys.fn_varbintohexstr, but as this post on dba.stackexchange.com explains, there are several reasons why you should avoid it.
CONVERT with style 2 to get a binary representation of the hexadecimal string;
... where TableA.bin_pk = CONVERT(VARBINARY, TableB.char_fk, 2)
The correct aproach is to set both fields in the same datatype. in order to to do this create a new table say temp and use select into and convert:
select field1,...,convert(varchar(50),varbinary(16),fieldToConvert)...,fieldN
into myNewTable
Found the answer. I need to use
master.dbo.fn_varbintohexstr (#source)
which converts a varbinary to varchar, and then works perfectly well for comparison in my scenario.

Conversion failed when converting date and/or time from character string

I have a fairly simple pagination query used to get rows from a table
ALTER PROCEDURE mytable.[news_editor_paginate]
#count int,
#start int,
#orderby int
AS
BEGIN
SET NOCOUNT ON;
SELECT TOP (#count) * FROM
(
SELECT news_edits.*,
ROW_NUMBER() OVER (
ORDER BY CASE
WHEN #orderby = 0 THEN news_edits.[time]
WHEN #orderby = 1 THEN news_edits.lastedit
WHEN #orderby = 2 THEN news_edits.title
END
DESC
) AS num
FROM news_edits
) AS a
WHERE num > #start
END
The #orderby parameter decides which column the results should be ordered by.
news_edit.[time] and news_edits.lastedit are both datetime fields. But news_edits.title is a varchar field.
The query runs fine for both the datetime fields but when #orderby = 2 I get the following error:
"Conversion failed when converting date and/or time from character string."
The problem I'm having is that I'm not trying to convert anything?
You'll need to divide your ORDER BY into multiple CASE statements:
ORDER BY
CASE WHEN #orderby = 0 THEN news_edits.[time] END DESC,
CASE WHEN #orderby = 1 THEN news_edits.lastedit END DESC,
CASE WHEN #orderby = 2 THEN news_edits.title END DESC
This is because single CASE statement requires that all branches have compatible data types. Since your character string in one CASE can't be converted to the date time returned from another CASE, you get the conversion error.
As you're not explicitly casting the "order by case..." values, SQL Server infers it's a datetime (according to the type of the first case).
The solution to your problem is to cast the dates in a string format that allows you to order by it, somewhat like 'yyyyMMddhhmmss'. If you do so, all the "order by case..." values will be chars and it will work.
Alternatively, you can have two selects, and choose one of them with an if. The first part of the if for the dates, the second for the title.