Discussion Locked

Sequel Server 7.0 data types.

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I have the following situation. I use a SQL Server database where one of the major key fields is defined as text field (string). This field contains nothing but a five-digit number. I am told by the people who installed the database that changing the data type of this field is a bad idea since it had been hard coded in the administrative module of the database (the database is iMIS, a commercial product).

I have acquired a new database which has a numeric key field (long integer), a five digit number, matching perfectly the key field of the other databse. I would like to relate tables of the two databases by this field, however I don't want to change the data type (long integer) of the second DB's key field.

Is there a way to link these databases without changing the key fields' datatype?

3 replies

by steved

That key field isn't really a Text data type, is it? I don't think SQL allows Text fields to be keys. If it's really Char or Varchar, then you have no major problem. You can join tables based on dissimilar data types as long as SQL can convert between the types.

Say you have these two tables:

TableA
------
KeyA varchar(10)
Data1 varchar(50)

TableB
------
KeyB int
DataB varchar(50)

There are two ways to join them. One allows SQL to convert implicitly, like this:

SELECT TableA.KeyA, TableA.Data1, TableB DataB
FROM TableA INNER JOIN TableB
ON TableA.KeyA = TableB.KeyB

In this example, SQL will try to convert the contents of KeyA to type int. If that ever fails due to non-numeric contents or too long a number, your join will fail.

The other way is safer because you specify an explicit conversion in the other direction, to a char type. This way there can't be any conversion errors:

SELECT TableA.KeyA, TableA.Data1, TableB DataB
FROM TableA INNER JOIN TableB
ON TableA.KeyA = Cast(TableB.KeyB as varchar(10))

One final thought: If it really is a text field (and they've figured out how to make it a key somehow) then why not create a view that has a new field derived from the text field that's of type varchar. Then do the join with the view instead of with the table.

I hope this helps.

Steve Diamond

by Former member

You are right, of course, it's a varchar field. I just didn't use the appropriate SQL data type terminology. Thanks, Steve!

by Former member

This question was closed by the author

This discussion is closed to new replies.