convert int to varchar working for SQL Server and MS-Access
Asked Answered
K

2

7

I must create a query compatible for SQL Server and MS-Access.

The problem is that in SQL Server I try to convert a number to varchar. In SQL Server I can do the conversion like this: convert(varchar(100), 5) in MS Access : CStr(5).

Are there possibilities to do this compatible for the both databases?

Kathline answered 26/3, 2013 at 14:30 Comment(0)
M
5

In SQL Server, you can write a user defined scalar function called CStr() that does the conversion.

The built-in routines are incompatible.

Unfortunately, this won't really work, because you need to prefix the function all with a schema name. So, you can have:

create function cstr(@val int)
returns varchar(255) as
begin return(cast(@val as varchar(255))) end;

But you have to call it as:

select dbo.cstr(4);

If the value is in a column, then consider writing a view on the table, in each database, that does the conversion in the view.

To get VB to work with both Access and SQL Server, you could just give up on Access and use a real database. Oh, I guess that's not a solution ;) You are going to need to identify the type of database and have different code for each one. You can minimize this by using views to hide some of the ugliness.

You might find it advantageous to switch to SQL Server 2012, which has expanded its repertoire of functions to include some Access functions. But not cstr().

Medor answered 26/3, 2013 at 14:32 Comment(1)
the problem is that I use this query in VB and I can connect a sql datebase or accessKathline
K
4

We can convert the number in varchar so:

  select format(Adress_ID,'0') ... next code

this code will convert from the both, Access and SQL Server

Kathline answered 26/3, 2013 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.