0

i was trying to search a single term on multiple columns. i got error because one of column was date time. how could i make a generic search with in-line sql. this way i tried.

create table tbl_test1
(id int identity(1,1),
column1 nvarchar(50),
coulmn2 nvarchar(50),
coulmn3 nvarchar(50),
coulmn4 datetime)-- Create a table 

insert into tbl_Test1 (column1,coulmn2,coulmn3,coulmn4) values
('Griff','Serjey','Maciej',GETDATE()),
('King','Fisher','Ajay',GETDATE()),
('Paul','Griff','Serjey',GETDATE()),
('King','Fisher','Griff',GETDATE())

select * from tbl_Test1 where 'Griff' IN (column1,coulmn2,coulmn3,coulmn4)

i got this error.

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

2
  • coulmn4 is datetime. Datetime is incompatible with string. You use it in IN clause. Commented Aug 29, 2016 at 9:24
  • @PawełDyl yes i know but looking for best idea. thanks Commented Aug 29, 2016 at 9:25

3 Answers 3

1

to fix your requirement, you can first convert column4, yourdatetime column to nvarchar(max) first

select * from tbl_Test1 where 'Griff' IN
 (column1,coulmn2,coulmn3,convert(nvarchar(max),coulmn4))

however this is not recommended to do so because of performance issues =x

Sign up to request clarification or add additional context in comments.

Comments

0

From 2012,,you can use..TRY_Convert

select * from #tbl_Test1 
where 'Griff'
 IN (column1,coulmn2,coulmn3,try_convert(varchar(10),coulmn4))

You may need to do similar cast and convert on other columns when you search with date columns

3 Comments

getting error when execute your code the error is 'varchar' is not a recognized built-in function name.
if i use convert instead of try_convert then all goes fine but try_convert throwing error 'varchar' is not a recognized built-in function name. i am using SQL Server 2012.
may be you are using try_convert like this..try_convert (columnname,varchar)
0

You already know that your column4 is of type datetime then why do we search your string with that column. Just ignore that column

Try like this,

SELECT *
FROM tbl_test1
WHERE 'Griff' IN (
        column1
        ,coulmn2
        ,coulmn3
        )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.