cannot convert varchar to float in sql - sql

These are my 2 tables
CREATE TABLE [dbo].[dailyRate](
[SYMBOL] [varchar](50) NULL,
[SERIES] [varchar](50) NULL,
[OPENPRICE] [varchar](50) NULL,
[HIGHPRICE] [varchar](50) NULL,
[LOWPRICE] [varchar](50) NULL,
[CLOSEPRICE] [varchar](50) NULL,
[LASTPRICE] [varchar](50) NULL,
[PREVCLOSE] [varchar](50) NULL,
[TOTTRDQTY] [varchar](50) NULL,
[TOTTRDVAL] [varchar](50) NULL,
[TIMESTAMPDAY] [varchar](50) NULL,
[TOTALTRADES] [varchar](50) NULL,
[ISIN] [varchar](50) NULL
)
CREATE TABLE [dbo].[cmpDailyRate](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[SYMBOL] [varchar](50) NULL,
[SERIES] [varchar](50) NULL,
[OPENPRICE] [decimal](18, 4) NULL,
[HIGHPRICE] [decimal](18, 4) NULL,
[LOWPRICE] [decimal](18, 4) NULL,
[CLOSEPRICE] [decimal](18, 4) NULL,
[LASTPRICE] [decimal](18, 4) NULL,
[PREVCLOSE] [decimal](18, 4) NULL,
[TOTTRDQTY] [bigint] NULL,
[TOTTRDVAL] [decimal](18, 4) NULL,
[TIMESTAMPDAY] [smalldatetime] NULL,
[TOTALTRADES] [bigint] NULL,
[ISIN] [varchar](50) NULL,
[M_Avg] [decimal](18, 4) NULL
)
this is my insert query to fetch data from table to another with casting
Collapse | Copy Code
INSERT into [Stock].[dbo].[cmpDailyRate]
SELECT [SYMBOL],[SERIES],Str([OPENPRICE], 18,4),Str([HIGHPRICE],18,4),
Str([LOWPRICE],18,4),Str([CLOSEPRICE],18,4),Str([LASTPRICE],18,4),Str([PREVCLOSE],18,4),convert(bigint,[TOTTRDQTY]),Str([TOTTRDVAL],18,4),
convert(date, [TIMESTAMPDAY], 105),convert(bigint,[TOTALTRADES]),[ISIN],null
FROM [Stock].[dbo].[DailyRate]
This query runs perfectly in SQL Server 2005, but it's causing errors in SQL Server 2008 (above query run also in SQL Server 2008 when installed; error arise in last few days)
Error :
Error cannot convert varchar to float
What to do?

One of your rows contains invalid data in the columns you are doing the float conversion (Str) on. Use the following strategy to work out which:
SELECT *
FROM [dailyRate]
WHERE IsNumeric([OPENPRICE]) = 0
OR IsNumeric([HIGHPRICE]) = 0
etc etc.

If you do not want to filter out data, a CASE statement might work better for you.
SELECT CASE
WHEN IsNumeric([OPENPRICE]) = 1 THEN [OPENPRICE]
ELSE NULL -- or 0 or whatever
END AS OPENPRICE,
CASE
WHEN IsNumeric([HIGHPRICE]) = 1 THEN [HIGHPRICE]
ELSE NULL -- or 0 or whatever
END AS [HIGHPRICE]
FROM [dailyRate]

Related

Brent Ozar's SQL Check Scripts - Memory/CPU/IO Concerns?

How careful do I need to be using Brent Ozar's free SQL health check scripts on a SQL Server 2016 production machine that's very full and very busy already? Has anyone run into memory, CPU or I/O issues running any of the following? Thanks for any feedback.
sp_Blitz
sp_BlitzCache
sp_BlitzFirst
sp_BlitzIndex
sp_BlitzLock
sp_BlitzQueryStore
sp_BlitzWho
sp_WhoIsActive (Adam Machanic)
I would not be without it. We have Redgate and I use Brents tools more often.
Our database is 3 Tb and has approx. 1500 queries per second and have never experienced any problems.
Made a custom sp_BlitzWho_Ext which relys on the sp_BlitzWho.
It takes the result of sp_BlitzWho. Puts it in a temp table so I can add a filter. Also cursors are identified and converted so you can see the actual query.
The SQL for dropping the plan_cache of each of them are there - so whenever we get a dumb plan its easy to find and drop the right one.
It now only takes 5 seconds to identify the culprit and get the plan dropped.
First I created a Function to get the query text from the Cursor
create function [dbo].[CursorQuery]
(
#session_id int
) returns nvarchar(255)
as
begin
declare #ret nvarchar(255) = null
SELECT #ret = t.text
FROM sys.dm_exec_cursors (#session_id) c
LEFT JOIN sys.dm_exec_sessions AS es ON c.session_id = es.session_id
CROSS APPLY sys.dm_exec_sql_text (c.sql_handle) t
return #ret
end
Then the stored procedure
CREATE PROCEDURE [dbo].[sp_BlitzWho_Ext]
AS
BEGIN
CREATE TABLE #BlitzWhoResult
(
[run_date] VARCHAR(255),
[elapsed_time] [varchar](41) NULL,
[session_id] [smallint] NOT NULL,
[database_name] [nvarchar](128) NULL,
[query_text] [nvarchar](max) NULL,
[query_plan] [xml] NULL,
[live_query_plan] [xml] NULL,
[query_cost] [float] NULL,
[status] [nvarchar](30) NOT NULL,
[wait_info] [nvarchar](max) NULL,
[top_session_waits] [nvarchar](max) NULL,
[blocking_session_id] [smallint] NULL,
[open_transaction_count] [int] NULL,
[is_implicit_transaction] [int] NOT NULL,
[nt_domain] [nvarchar](128) NULL,
[host_name] [nvarchar](128) NULL,
[login_name] [nvarchar](128) NOT NULL,
[nt_user_name] [nvarchar](128) NULL,
[program_name] [nvarchar](128) NULL,
[fix_parameter_sniffing] [nvarchar](150) NULL,
[client_interface_name] [nvarchar](32) NULL,
[login_time] [datetime] NOT NULL,
[start_time] [datetime] NULL,
[request_time] [datetime] NULL,
[request_cpu_time] [int] NULL,
[request_logical_reads] [bigint] NULL,
[request_writes] [bigint] NULL,
[request_physical_reads] [bigint] NULL,
[session_cpu] [int] NOT NULL,
[session_logical_reads] [bigint] NOT NULL,
[session_physical_reads] [bigint] NOT NULL,
[session_writes] [bigint] NOT NULL,
[tempdb_allocations_mb] [decimal](38, 2) NULL,
[memory_usage] [int] NOT NULL,
[estimated_completion_time] [bigint] NULL,
[percent_complete] [real] NULL,
[deadlock_priority] [int] NULL,
[transaction_isolation_level] [varchar](33) NOT NULL,
[degree_of_parallelism] [smallint] NULL,
[last_dop] [bigint] NULL,
[min_dop] [bigint] NULL,
[max_dop] [bigint] NULL,
[last_grant_kb] [bigint] NULL,
[min_grant_kb] [bigint] NULL,
[max_grant_kb] [bigint] NULL,
[last_used_grant_kb] [bigint] NULL,
[min_used_grant_kb] [bigint] NULL,
[max_used_grant_kb] [bigint] NULL,
[last_ideal_grant_kb] [bigint] NULL,
[min_ideal_grant_kb] [bigint] NULL,
[max_ideal_grant_kb] [bigint] NULL,
[last_reserved_threads] [bigint] NULL,
[min_reserved_threads] [bigint] NULL,
[max_reserved_threads] [bigint] NULL,
[last_used_threads] [bigint] NULL,
[min_used_threads] [bigint] NULL,
[max_used_threads] [bigint] NULL,
[grant_time] [varchar](20) NULL,
[requested_memory_kb] [bigint] NULL,
[grant_memory_kb] [bigint] NULL,
[is_request_granted] [varchar](39) NOT NULL,
[required_memory_kb] [bigint] NULL,
[query_memory_grant_used_memory_kb] [bigint] NULL,
[ideal_memory_kb] [bigint] NULL,
[is_small] [bit] NULL,
[timeout_sec] [int] NULL,
[resource_semaphore_id] [smallint] NULL,
[wait_order] [varchar](20) NULL,
[wait_time_ms] [varchar](20) NULL,
[next_candidate_for_memory_grant] [varchar](3) NOT NULL,
[target_memory_kb] [bigint] NULL,
[max_target_memory_kb] [varchar](30) NULL,
[total_memory_kb] [bigint] NULL,
[available_memory_kb] [bigint] NULL,
[granted_memory_kb] [bigint] NULL,
[query_resource_semaphore_used_memory_kb] [bigint] NULL,
[grantee_count] [int] NULL,
[waiter_count] [int] NULL,
[timeout_error_count] [bigint] NULL,
[forced_grant_count] [varchar](30) NULL,
[workload_group_name] [sysname] NULL,
[resource_pool_name] [sysname] NULL,
[context_info] [varchar](128) NULL,
[query_hash] [binary](8) NULL,
[query_plan_hash] [binary](8) NULL,
[sql_handle] [varbinary] (64) NULL,
[plan_handle] [varbinary] (64) NULL,
[statement_start_offset] INT NULL,
[statement_end_offset] INT NULL
)
INSERT INTO #BlitzWhoResult
EXEC [dbo].[sp_BlitzWho] #ShowSleepingSPIDs = 1, #ExpertMode = 1, #MinElapsedSeconds = 1
SELECT [program_name],
[session_id],
CASE WHEN [query_text] LIKE 'FETCH API_CURSOR%'
THEN CursorQuery(session_id)
ELSE query_text
END AS [query_text],
[query_plan],
[fix_parameter_sniffing] AS [drop_cached_plan_sql],
[status],
[wait_info],
[login_name]
from #BlitzWhoResult
where database_name = 'PUT_YOUR_DATABASENAME_HERE' -- and... add more filters?
DROP TABLE #BlitzWhoResult
END
So.. I really enjoy Brents tool as well as his videos and sense of humour

SQL Between Function - Wrong Data is reflecting

I am trying to extract the data using between function but wrong data is reflecting
below SQL query i am using,
select * from ORDERSTATUS where ORDERDATE BETWEEN '25-07-2017' AND '31-08-2017';
Also when i run below sql query to extract the data of particular date, i am getting correct output.
select * from ORDERSTATUS where ORDERDATE = '31-08-2017'
Please help me....
and below is the design of my table,
[VENCD] [varchar](50) NOT NULL,
[VENNAME] [varchar](255) NOT NULL,
[ITEMCD] [varchar](50) NOT NULL,
[ITEMNAME] [varchar](255) NOT NULL,
[SKUCD] [varchar](50) NULL,
[SKUNAME] [varchar](255) NULL,
[OORDERNO] [varchar](50) NOT NULL,
[INVNO] [varchar](50) NULL,
[OQTY] [int] NOT NULL,
[COD] [int] NOT NULL,
[SELLINGPRICE] [int] NOT NULL,
[ORDERTYPE] [varchar](50) NOT NULL,
[DSP] [varchar](50) NOT NULL,
[DOCKETNO] [varchar](50) NULL,
[MANIFESTID] [varchar](100) NULL,
**[ORDERDATE] [varchar](50) NOT NULL,**
[CANCELDATE] [varchar](50) NULL,
[SHIPP_INST_DATE] [varchar](50) NULL,
[INVOUTDATE] [varchar](50) NULL,
[PICKUPDATE] [varchar](50) NULL,
[REALDELDATE] [varchar](50) NULL,
[DELCOMPDATE] [varchar](50) NULL,
[RETURNREGDATE] [varchar](50) NULL,
[SHIPP_CANCELDATE] [varchar](50) NULL,
[RTODATE] [varchar](50) NULL,
[DRDATE] [varchar](50) NULL,
[PROSSSTAGE] [varchar](255) NOT NULL,
[REFUND] [varchar](50) NOT NULL,
[CHNLCODE] [varchar](50) NOT NULL,
[CHNLCLASS] [varchar](50) NOT NULL,
[HLCN] [varchar](50) NULL,
[MLCN] [varchar](50) NULL,
[COMMPERC] [int] NULL,
[EXCHCANCELDATE] [varchar](50) NULL,
[RETURNCANCELDATE] [varchar](50) NULL,
[TYPE] [varchar](50) NULL
Can you change where clause with this?
CONVERT (DATETIME, ORDERDATE, 105) BETWEEN '20170725' AND '20170831';
Just use :
WHERE CONVERT(DATE, ORDERDATE) BETWEEN '20170725' AND '20170831'

SQL server sys.dm_db_index_physical_stats Remote scan in query plan

I have a query in db A which shows the index fragmentation level and recent rebuilt or re-organised status, it cross apply a function B in db C, A and C are on the same instance.
Function B is:
ALTER function [dbo].[B]
(
#db_id int
,#object_id int
,#index_id int
,#partition_number int
,#mode varchar (20)
)
returns #results TABLE (
[database_id] [smallint] NULL,
[object_id] [int] NULL,
[index_id] [int] NULL,
[partition_number] [int] NULL,
[index_type_desc] [nvarchar](60) NULL,
[alloc_unit_type_desc] [nvarchar](60) NULL,
[index_depth] [tinyint] NULL,
[index_level] [tinyint] NULL,
[avg_fragmentation_in_percent] [float] NULL,
[fragment_count] [bigint] NULL,
[avg_fragment_size_in_pages] [float] NULL,
[page_count] [bigint] NULL,
[avg_page_space_used_in_percent] [float] NULL,
[record_count] [bigint] NULL,
[ghost_record_count] [bigint] NULL,
[version_ghost_record_count] [bigint] NULL,
[min_record_size_in_bytes] [int] NULL,
[max_record_size_in_bytes] [int] NULL,
[avg_record_size_in_bytes] [float] NULL,
[forwarded_record_count] [bigint] NULL,
[compressed_page_count] [bigint] NULL
)
begin
insert into #results
select *
from sys.dm_db_index_physical_stats (#db_id, #object_id, #index_id ,#partition_number
,#mode )
return
end
This query takes a long time to execute. I read the query plan, the plan contains a "Remote Scan". I don't understand why is that.
Can anyone help?
Thanks,

Can someone break down a PIVOT query for me please?

I am looking to pivot this data so the output can count how many people are in each age band...
Below is what I have done, but I don't even think I'm close....
I am using SQL Server 2008
SELECT [OA_Code], Dominant_F_Age, Age_F_90plus, Age_F_85_89, Age_F_80_84, Age_F_75_79, Age_F_70_74, Age_F_65_69, Age_F_60_64,
Age_F_55_59, Age_F_50_54, Age_F_45_49, Age_F_40_44, Age_F_35_39, Age_F_30_34, Age_F_25_29, Age_F_20_24, Age_F_15_19, Age_F_10_14, Age_F_5_9,
Age_F_0_4, Age_2001_F
FROM cen.AgeByGenderOA
PIVOT (
f_Age_data
for [F_Age_Data] in (Age_F_90plus, Age_F_85_89, Age_F_80_84, Age_F_75_79, Age_F_70_74, Age_F_65_69, Age_F_60_64,
Age_F_55_59, Age_F_50_54, Age_F_45_49, Age_F_40_44, Age_F_35_39, Age_F_30_34, Age_F_25_29, Age_F_20_24, Age_F_15_19, Age_F_10_14, Age_F_5_9),
Age_F_0_4)
My table looks like so:
CREATE TABLE AgeByGenderOA(
[OA_Code] AS VARCHAR(50),
[Age_M_0_4] [varchar](50) NULL,
[Age_M_5_9] [varchar](50) NULL,
[Age_M_10_14] [varchar](50) NULL,
[Age_M_15_19] [varchar](50) NULL,
[Age_M_20_24] [varchar](50) NULL,
[Age_M_25_29] [varchar](50) NULL,
[Age_M_30_34] [varchar](50) NULL,
[Age_M_35_39] [varchar](50) NULL,
[Age_M_40_44] [varchar](50) NULL,
[Age_M_45_49] [varchar](50) NULL,
[Age_M_50_54] [varchar](50) NULL,
[Age_M_55_59] [varchar](50) NULL,
[Age_M_60_64] [varchar](50) NULL,
[Age_M_65_69] [varchar](50) NULL,
[Age_M_70_74] [varchar](50) NULL,
[Age_M_75_79] [varchar](50) NULL,
[Age_M_80_84] [varchar](50) NULL,
[Age_M_85_89] [varchar](50) NULL,
[Age_M_90plus] [varchar](50) NULL,
[Dominant_M_Age] [varchar](50) NULL,
[Age_2001_F] [varchar](50) NULL,
[Age_F_0_4] [varchar](50) NULL,
[Age_F_5_9] [varchar](50) NULL,
[Age_F_10_14] [varchar](50) NULL,
[Age_F_15_19] [varchar](50) NULL,
[Age_F_20_24] [varchar](50) NULL,
[Age_F_25_29] [varchar](50) NULL,
[Age_F_30_34] [varchar](50) NULL,
[Age_F_35_39] [varchar](50) NULL,
[Age_F_40_44] [varchar](50) NULL,
[Age_F_45_49] [varchar](50) NULL,
[Age_F_50_54] [varchar](50) NULL,
[Age_F_55_59] [varchar](50) NULL,
[Age_F_60_64] [varchar](50) NULL,
[Age_F_65_69] [varchar](50) NULL,
[Age_F_70_74] [varchar](50) NULL,
[Age_F_75_79] [varchar](50) NULL,
[Age_F_80_84] [varchar](50) NULL,
[Age_F_85_89] [varchar](50) NULL,
[Age_F_90plus] [varchar](50) NULL,
[Dominant_F_Age] [varchar](50) NULL,
[MAPINFO_ID] [varchar](50) NULL)
As you can see it's a huge table. The "Age_M_0_4" columns are populated with numbers.
I would like my output to read
OA_Code, Age, countOfAge
123456, Age_0_4, 26
123456, Age_5_9, 24
789456, Age_0_4, 10
789456, Age_5_9, 12
This would be inclusive of male and female ages.
Anyone fancy taking a crack at this one?
Finally: The data contained in the "Age_M_" Columns is all numbers counts. 50, 40, 2, 0 etc...
You do not want a PIVOT, you need to UNPIVOT the data. Since you are using SQL Server 2008+, you can use CROSS APPLY with a VALUES clause. The code will be similar to this:
select t.OA_Code,
c.age,
sum(cast(c.value as int)) countOfAge
from AgeByGenderOA t
cross apply
(
values
('Age_0_4', Age_M_0_4),
('Age_5_9', Age_M_5_9),
('Age_10_14', Age_M_10_14),
('Age_15_19', Age_M_15_19) ... add the other columns here
) c (age, value)
group by t.OA_Code, c.age
See SQL Fiddle with Demo
Edit, If you want both Male/Female columns you will include ALL of the columns in the values clause, but give them the same age range value:
select t.OA_Code,
c.age,
sum(cast(c.value as int)) countOfAge
from AgeByGenderOA t
cross apply
(
values
('Age_0_4', Age_M_0_4),
('Age_5_9', Age_M_5_9),
('Age_10_14', Age_M_10_14),
('Age_15_19', Age_M_15_19),
('Age_0_4', Age_F_0_4),
('Age_5_9', Age_F_5_9),
('Age_10_14', Age_F_10_14),
('Age_15_19', Age_F_15_19)
) c (age, value)
group by t.OA_Code, c.age;
See SQL Fiddle with Demo

Joining multiple columns in one table to a single column in another table

I am looking to create a view that pulls data from two tables "Schedule" and "Reference".
Schedule has 50+ columns (it's almost completely denormalized -- not my design), most of which contain a value that could be joined to a column in the Reference table.
How do I write the SQL statement to correctly join each column in Schedules to the single column in Reference?
The Schedule table is defined as:
CREATE TABLE [dbo].[Schedule](
[ID] [int] NOT NULL,
[SCHEDULEWEEK] [datetime] NOT NULL,
[EMPNO] [numeric](10, 0) NOT NULL,
[EMPLNAME] [varchar](32) NULL,
[EMPFNAME] [varchar](32) NULL,
[EMPSENDATE] [datetime] NULL,
[EMPHIREDATE] [datetime] NULL,
[EMPTYPE] [char](1) NULL,
[EMPSTATUS] [char](1) NULL,
[SNREFUSALS] [tinyint] NULL,
[QUALSTRING] [varchar](128) NULL,
[JOBOVERSHIFTTYPE] [bit] NULL,
[SHORTNOTICE] [bit] NULL,
[SHORTNOTICEWAP] [bit] NULL,
[SHORTNOTICEPHONE] [varchar](32) NULL,
[LEADHAND] [bit] NULL,
[DUALCURRENCY] [bit] NULL,
[MIN100WINDOW] [bit] NULL,
[STATHOLIDAY] [bit] NULL,
[AREAOVERHOURS] [bit] NULL,
[DOUBLEINTERZONES] [bit] NULL,
[MAXDAYSPERWEEK] [tinyint] NULL,
[MAXHOURSPERWEEK] [numeric](10, 2) NULL,
[MAXHOURSPERSHIFT] [numeric](10, 2) NULL,
[MAXDOUBLESPERWEEK] [tinyint] NULL,
[ASSIGNEDDAYS] [tinyint] NULL,
[ASSIGNEDHOURS] [numeric](10, 2) NULL,
[ASSIGNEDDOUBLES] [tinyint] NULL,
[ASSIGNEDLOAHOURS] [numeric](10, 2) NULL,
[SHIFTNO1] [int] NULL,
[TEXT1_1] [varchar](64) NULL,
[TEXT2_1] [varchar](64) NULL,
[DAYFLAG1] [bit] NULL,
[COMMENT1] [text] NULL,
[SHIFTNO2] [int] NULL,
[TEXT1_2] [varchar](64) NULL,
[TEXT2_2] [varchar](64) NULL,
[DAYFLAG2] [bit] NULL,
[COMMENT2] [text] NULL,
[SHIFTNO3] [int] NULL,
[TEXT1_3] [varchar](64) NULL,
[TEXT2_3] [varchar](64) NULL,
[DAYFLAG3] [bit] NULL,
[COMMENT3] [text] NULL,
[SHIFTNO4] [int] NULL,
[TEXT1_4] [varchar](64) NULL,
[TEXT2_4] [varchar](64) NULL,
[DAYFLAG4] [bit] NULL,
[COMMENT4] [text] NULL,
[SHIFTNO5] [int] NULL,
[TEXT1_5] [varchar](64) NULL,
[TEXT2_5] [varchar](64) NULL,
[DAYFLAG5] [bit] NULL,
[COMMENT5] [text] NULL,
[SHIFTNO6] [int] NULL,
[TEXT1_6] [varchar](64) NULL,
[TEXT2_6] [varchar](64) NULL,
[DAYFLAG6] [bit] NULL,
[COMMENT6] [text] NULL
-- Snip
) ON [PRIMARY]
And the Reference table is defined as:
CREATE TABLE [dbo].[Reference](
[ID] [int] NOT NULL,
[CODE] [varchar](21) NOT NULL,
[LOCATIONCODE] [varchar](4) NOT NULL,
[SCHAREACODE] [varchar](16) NOT NULL,
[LOCATIONNAME] [varchar](32) NOT NULL,
[FLTAREACODE] [varchar](16) NOT NULL
) ON [PRIMARY]
I am trying to join each [TEXT1_]/[TEXT2_] column in Schedule to the [SCHAREACODE] column in reference. All the reference table contains is a list of areas where the employee could work.
I think he means to join on the Reference table multiple times:
SELECT *
FROM Schedule AS S
INNER JOIN Reference AS R1
ON R1.ID = S.FirstID
INNER JOIN Reference AS R2
ON R2.ID = S.SecondID
INNER JOIN Reference AS R3
ON R3.ID = S.ThirdID
INNER JOIN Reference AS R4
ON R4.ID = S.ForthID
Your description is a bit lacking, so I'm going to assume that
Schedule has 50+ columns (it's almost completely denormalized -- not my design), most of which contain a value that could be joined to a column in the Reference table.
means that 1 of the 50+ columns in Schedule is a ReferenceId. So, given a table design like:
Schedule ( MaybeReferenceId1, MaybeReferenceId2, MaybeReferenceId3, ... )
Reference ( ReferenceId )
Something like:
SELECT *
FROM Schedule
JOIN Reference ON
Schedule.MaybeReferenceId1 = Reference.ReferenceId
OR Schedule.MaybeReferenceId2 = Reference.ReferenceId
OR Schedule.MaybeReferenceId3 = Reference.ReferenceId
OR Schedule.MaybeReferenceId4 = Reference.ReferenceId
...
would work. You could simplify it by using IN if your RDBMS supports it:
SELECT *
FROM Schedule
JOIN Reference ON
Reference.ReferenceId IN (
Schedule.MaybeReferenceId1,
Schedule.MaybeReferenceId2,
Schedule.MaybeReferenceId3,
Schedule.MaybeReferenceId4,
...
)
From updated question
Perhaps something like this? It will be messy no matter what you do.
SELECT S.ID
S.TEXT1_1,
TEXT1_1_RID = COALESCE((SELECT MAX(R.ID) FROM Reference R WHERE R.SCHAREACODE = S.TEXT1_1), 0),
S.TEXT1_2,
TEXT1_2_RID = COALESCE((SELECT MAX(R.ID) FROM Reference R WHERE R.SCHAREACODE = S.TEXT1_2), 0),
...
FROM Schedule S
Agree with TheSoftwareJedi, but can I just suggest using LEFT JOINs so that failures-to-match don't cause your Schedule row to disappear?
Of course, doing 28 JOINs is going to be a bit cumbersome whatever the details.
I'm not sure I'd call this "denormalized", more "abnormalized" ... :-)
Try a query like this:
select s.*, r.schareacode from schedule s,
where
s.text1_1 = s.schareacode
or s.text2_1 = s.schareacode
or s.textx_x = s.schareacode
..
You should be able to get the same results with traditional joins so I recommend you experiment with that as well.