I have a question about a specific query I’m writing in a SQL Server 2008 database. This is part of a (much) larger query, but I’ll simplify the hell out of it to make it easier to isolate what I’m trying to do.
I have a table TableX, two columns:
IDX (int) identityVarX (varchar(20))
I have two auxiliary tables, TableY and TableZ. Both have two columns,
TableY
-
IDY (int) identity -
VarY (varchar(20))and
TableZ -
IDZ (int) identity -
VarZ (varchar(20))
I am doing an insert into a fourth table, we’ll call it TableA. TableA has three columns:
IDA (int) identityIDY (int)IDZ (int)
The IDY and IDZ fields in this table are foreign keys to the identity columns in Table Y and Table Z.
Sounds complicated, but its a really simple connection. Here’s where it gets fun though.
So the data in TableX might look like this:
IDX | VarX
--------------
1 | ABC
2 | ABC-LMN
The data in TableY:
IDY | VarY
----------------
1 |ABC
2 | HIJ
The data in TableZ:
IDZ | VarZ
----------------
1 | LMN
2 | OPQ
Basically, VarX (the second column), is either going to be a single varchar string, or two connected by a hyphen, no spaces. In the case of a single string, with no hyphen, its always a match in Table Y. The match would be on VarY in TableY = VarX in TableX. I would grab the associated ID (IDY), and use that in the insert on TableA.
In the example of row 1, the insert into TableA would be (null, 1, null)
Now in the case of row 2, it has two strings separated by a hyphen. So the insert into TableA would ultimately be (null, 1, 1).
So my question is this… how do I formulate the insert with its corresponding joins to deal with this type of logic? I’m sure it has to be a case statement… just having alot of trouble visualizing the full query, as I’m no DBA…. Any help is appreciated.
There’s no need to make this dynamic SQL, unless the proc this is part of requires it.
I have intentionally omitted inserting NULL in to
TableA.IDA, as I don’t know why you’d want to try inserting NULL in to an identity column, or if that’s even possible. I have also assumed that the data inVarXwill not have degenerate cases, such as'-','ZXC-','ASD-BNM ', etc.