Skip to content
Advertisement

Create a view in SQL Server and lookup with another table

I’m very new to SQL and am trying to create a view in SQL Server using 2 tables. There are some conditions will impact the way of selecting data and I would appreciate some guidance on what’s the logic to create a view for my requirements.

Condition: if the Description in Table1 is more than 10 characters and the character from the 9th to 11th are all numbers (3 numbers), then lookup in Table2 with the same Device_Name and Number. If there’s a match, select the Host_Name (T2) and replace the Device_Name in the view.

Example:

“Ethernet100” is more than 10 characters and there are all number from the 9th and 11th, use the number 100 and Device_name to lookup at Table2. Replace the Device_Name with Host_Name and put the Host_Name at the new column in the view [Host_On].

Table 1

Table 2

Desired result:

Any advice or small part of code is appreciated.

Advertisement

Answer

SUBSTRING return empty string if string shorter than required.

TRY_CONVERT() return NULL if string isn’t numeric

SQL DEMO

OUTPUT as you can see 1/1 doesnt match anything and get Host NULL

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement