Generate missing rows using JOIN / CROSS JOIN - sql

I have 3 tables which are used to fill dynamic from value.
The table is represented by schema below.
User can add as many rows as possible, and the rows are shown to end user by template from FormField table.
The data that is saved in FormValues are only for not null values and any values that missing are not saved.
Now the problem is I have to generate report as expected below.
I have tried various combination of join / cross join, but none of them works as expected.
I am able to achieve this in C# via loops, but not able to do the same via SQL Server.
Script attached for DB
USE [SampleDb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FormTemplate](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_FormTemplate] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FormField](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FormId] [int] NOT NULL,
[FieldName] [nvarchar](50) NULL,
[FieldType] [nvarchar](50) NULL,
CONSTRAINT [PK_FormField] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[FormTemplate] Script Date: 3/2/2020 10:10:22 PM ******/
/****** Object: Table [dbo].[FormValue] Script Date: 3/2/2020 10:10:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FormValue](
[FormId] [int] NOT NULL,
[FieldId] [int] NOT NULL,
[RowIndex] [int] NOT NULL,
[FormValue] [nvarchar](50) NULL,
CONSTRAINT [PK_FormValue] PRIMARY KEY CLUSTERED
(
[FormId] ASC,
[FieldId] ASC,
[RowIndex] ASC
)
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[FormField] ON
GO
INSERT [dbo].[FormField] ([Id], [FormId], [FieldName], [FieldType]) VALUES (1, 1, N'FirstName', N'string')
GO
INSERT [dbo].[FormField] ([Id], [FormId], [FieldName], [FieldType]) VALUES (2, 1, N'LastName', N'string')
GO
INSERT [dbo].[FormField] ([Id], [FormId], [FieldName], [FieldType]) VALUES (3, 1, N'Place', N'string')
GO
INSERT [dbo].[FormField] ([Id], [FormId], [FieldName], [FieldType]) VALUES (4, 1, N'age', N'int')
GO
INSERT [dbo].[FormField] ([Id], [FormId], [FieldName], [FieldType]) VALUES (5, 1, N'dob', N'date')
GO
SET IDENTITY_INSERT [dbo].[FormField] OFF
GO
SET IDENTITY_INSERT [dbo].[FormTemplate] ON
GO
INSERT [dbo].[FormTemplate] ([Id], [Name]) VALUES (1, N'Sample')
GO
SET IDENTITY_INSERT [dbo].[FormTemplate] OFF
GO
INSERT [dbo].[FormValue] ([FormId], [FieldId], [RowIndex], [FormValue]) VALUES (1, 1, 1, N'fname1')
GO
INSERT [dbo].[FormValue] ([FormId], [FieldId], [RowIndex], [FormValue]) VALUES (1, 2, 1, N'lname1')
GO
INSERT [dbo].[FormValue] ([FormId], [FieldId], [RowIndex], [FormValue]) VALUES (1, 2, 3, N'lname3')
GO
INSERT [dbo].[FormValue] ([FormId], [FieldId], [RowIndex], [FormValue]) VALUES (1, 4, 5, N'20')
GO
INSERT [dbo].[FormValue] ([FormId], [FieldId], [RowIndex], [FormValue]) VALUES (1, 5, 3, N'10/10/2020')
GO

This answers the original version of the question -- and then some. But I don't update answers to conform to evolving questions.
You seem to want cross joins on three "tables". The third needs to generate the rowindex values:
select f.id as formtemplateid, ff.id as formfieldid, v.rowindex,
fv.value
from formtemplate f cross join
formfield ff cross join
(values (1), (2), (3), (4), (5)) v(rowindex) left join
formvalues fv
on fv.formtemplateid = f.id and
fv.formfieldid = ff.id and
fv.rowindex = v.rowindex
order by f.id, ff.id, v.rowindex;
EDIT:
You can generate up to 100 numbers using a recursive CTE by doing:
with n as (
select 1 as n
union all
select n + 1
from n
where n < 10 -- "10" is however many you want
)
select n.n
from n;

Related

How to return "most populated","least populated" countries grouped by continent organized in a single table via SQL?

This is a variant of the SQLzoo tutorial.
'world' table contains fields
'population'(assigned to each country),
'name' (all countries) and
'continent' (assigned to each country).
Expected output is a table as shown below
Continent
Most_populous
Least_populous
Africa
Ghana
xyz
Asia
China
abc
I did try a complicated function as below, but was not able to get it to work due to "SQL error". Not sure why.
SELECT DISTINCT continent
, (SELECT x.name
FROM world x
WHERE x.population = (SELECT max(y.population)
FROM world y
WHERE x.continent = y.continent)) AS most_populous
, (SELECT z.name
FROM world z
WHERE z.population = (SELECT min(a.population)
FROM world a
WHERE a.continent=z.continent)) AS least_populous FROM world;
Is there an easier way to get the required output?
You can try this:
SELECT world.continent,
(SELECT x.name
FROM world x
WHERE x.population = (SELECT max(y.population)
FROM world y
WHERE x.continent = y.continent)
AND world.continent = x.continent
) AS most_populous,
(SELECT z.name
FROM world z
WHERE z.population = (SELECT min(a.population)
FROM world a
WHERE z.continent = a.continent)
AND world.continent = z.continent
) AS least_populous
FROM world
GROUP BY world.continent;
Thank you
Since I did not had the tables with me, I ended up creating one. It would be better if you could include table and data creation scripts in question. Second, this is going to be a fairly small table so I am not going to worry about performance. I would create a view based on this query and that will be good enough.
Table creation scripts:
USE [StackOverflow]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CountryPopulation]') AND type in (N'U'))
DROP TABLE [dbo].[CountryPopulation]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CountryPopulation](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[Continent] [nvarchar](max) NULL,
[Population] [int] NULL,
CONSTRAINT [PK_CountryPopulation] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
USE [StackOverflow]
GO
SET IDENTITY_INSERT [dbo].[CountryPopulation] ON
GO
INSERT [dbo].[CountryPopulation] ([ID], [Name], [Continent], [Population]) VALUES (1, N'C1', N'Asia', 100)
GO
INSERT [dbo].[CountryPopulation] ([ID], [Name], [Continent], [Population]) VALUES (2, N'C2', N'Asia', 200)
GO
INSERT [dbo].[CountryPopulation] ([ID], [Name], [Continent], [Population]) VALUES (3, N'C3', N'Asia', 300)
GO
INSERT [dbo].[CountryPopulation] ([ID], [Name], [Continent], [Population]) VALUES (4, N'C4', N'Europe', 100)
GO
INSERT [dbo].[CountryPopulation] ([ID], [Name], [Continent], [Population]) VALUES (5, N'C5', N'Europe', 200)
GO
INSERT [dbo].[CountryPopulation] ([ID], [Name], [Continent], [Population]) VALUES (6, N'C6', N'Europe', 300)
GO
INSERT [dbo].[CountryPopulation] ([ID], [Name], [Continent], [Population]) VALUES (7, N'C7', N'Africa', 100)
GO
INSERT [dbo].[CountryPopulation] ([ID], [Name], [Continent], [Population]) VALUES (8, N'C8', N'Africa', 200)
GO
INSERT [dbo].[CountryPopulation] ([ID], [Name], [Continent], [Population]) VALUES (9, N'C9', N'Africa', 200)
GO
SET IDENTITY_INSERT [dbo].[CountryPopulation] OFF
GO
Query to get result:
SELECT MinMax.Continent,
ForLeast.[name] AS LeastPopulous,
ForMost.[name] AS MostPopulous
FROM CountryPopulation ForMost JOIN
CountryPopulation ForLeast JOIN
( SELECT DISTINCT Continent,
MIN([population]) OVER(PARTITION BY continent) AS LeastPopulation,
MAX([population]) OVER(PARTITION BY continent) AS MaxPopulation
FROM CountryPopulation) MinMax
ON ForLeast.Continent = MinMax.Continent AND ForLeast.[Population] = MinMax.LeastPopulation
ON ForMost.Continent = MinMax.Continent AND ForMost.[Population] = MinMax.MaxPopulation
Note the results for Africa. There are 2 rows. It is possible for more than one country to have least or most population. You would want to think on how to handle that scenario.

Get Nested JSON from SQL table

Below is my table data looks like.
Below is SQL Query for Create table
CREATE TABLE [dbo].[CategoryMaster](
[CategoryId] [int] NOT NULL,
[ParentId] [int] NULL,
[Name] [varchar](50) NULL,
CONSTRAINT [PK_CategoryMaster] PRIMARY KEY CLUSTERED
(
[CategoryId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (1, NULL, N'Toys & Games')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (2, 1, N'Art And Crafts')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (3, 1, N'Baby & Toddler Toys')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (4, 1, N'Bikes, Trikes & Ride-Ons')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (5, 2, N'Aprons & Smocks')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (6, 2, N'Blackboards & Whiteboards')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (7, 2, N'Clay & Dough')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (8, 1, N'Pretend Play')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (9, 8, N'Kitchen Toys')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (10, 9, N'Cooking Appliances')
GO
INSERT [dbo].[CategoryMaster] ([CategoryId], [ParentId], [Name]) VALUES (11, 9, N'Cookware')
GO
ALTER TABLE [dbo].[CategoryMaster] WITH CHECK ADD CONSTRAINT [FK_CategoryMaster_CategoryMaster] FOREIGN KEY([ParentId])
REFERENCES [dbo].[CategoryMaster] ([CategoryId])
GO
ALTER TABLE [dbo].[CategoryMaster] CHECK CONSTRAINT [FK_CategoryMaster_CategoryMaster]
GO
I had tried many queries but not able to get desired result. can anyone please help me out from this situation?
I want output like below.
You can create a recursive function like below:
CREATE FUNCTION Create_Json(#CategoryId INT, #IsRoot INT)
RETURNS VARCHAR(MAX)
BEGIN
DECLARE #Json NVARCHAR(MAX) = '{}', #Name NVARCHAR(MAX), #Children NVARCHAR(MAX)
SET #Json = (SELECT P.[Name],JSON_QUERY(dbo.Create_Json(P.CategoryId, 2) ) AS Children
FROM [dbo].[CategoryMaster] AS P
WHERE P.ParentId = #CategoryId
FOR JSON AUTO);
IF(#IsRoot = 1)
BEGIN
SELECT #Name = P.[Name] FROM [dbo].[CategoryMaster] AS P WHERE P.CategoryId = #CategoryId
SET #Json = '"result": {"Name":"' + #Name + '","Children":' + CAST(#Json AS NVARCHAR(MAX)) + '}'
SET #IsRoot = 0
END
RETURN #Json
END
and call it like:
select dbo.Create_Json(1, 1)
Please find the db<>fiddle here.

Find non existing time intervall when doing join to another table

I have a question that I dont know If there is solution to in sql. Made an small example
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Events](
[Id] [int] IDENTITY(1,1) NOT NULL,
[EventTime] [datetime] NOT NULL,
[Event] [nvarchar](50) NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Logging] Script Date: 2020-07-07 14:35:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Logging](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FromTime] [datetime] NOT NULL,
[ToTime] [datetime] NOT NULL,
[Status] [nvarchar](50) NULL
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Events] ON
GO
INSERT [dbo].[Events] ([Id], [EventTime], [Event]) VALUES (1, CAST(N'2020-07-07T14:14:00.000' AS DateTime), N'str')
GO
INSERT [dbo].[Events] ([Id], [EventTime], [Event]) VALUES (2, CAST(N'2020-07-07T07:01:00.000' AS DateTime), N'testcall')
GO
INSERT [dbo].[Events] ([Id], [EventTime], [Event]) VALUES (3, CAST(N'2020-07-07T15:22:00.000' AS DateTime), N'ipfail')
GO
SET IDENTITY_INSERT [dbo].[Events] OFF
GO
SET IDENTITY_INSERT [dbo].[Logging] ON
GO
INSERT [dbo].[Logging] ([Id], [FromTime], [ToTime], [Status]) VALUES (1, CAST(N'2020-07-07T01:00:00.000' AS DateTime), CAST(N'2020-07-07T13:00:00.000' AS DateTime), N'All well')
GO
INSERT [dbo].[Logging] ([Id], [FromTime], [ToTime], [Status]) VALUES (2, CAST(N'2020-07-07T13:01:00.000' AS DateTime), CAST(N'2020-07-07T15:00:00.000' AS DateTime), N'All well')
GO
INSERT [dbo].[Logging] ([Id], [FromTime], [ToTime], [Status]) VALUES (3, CAST(N'2020-07-07T15:33:00.000' AS DateTime), CAST(N'2020-07-07T20:00:00.000' AS DateTime), N'All well')
GO
INSERT [dbo].[Logging] ([Id], [FromTime], [ToTime], [Status]) VALUES (4, CAST(N'2020-07-07T20:01:00.000' AS DateTime), CAST(N'2020-07-07T23:00:00.000' AS DateTime), N'All well')
GO
SET IDENTITY_INSERT [dbo].[Logging] OFF
GO
When doing an inner join of this table I want to find the Event in Event table that doesn't have a matching timeframe in Logging. The timeframe that's missing is 15:00 to 15:33 and the event that happens that happens is the Event with ID 3. Everything is measured in minutes. Is this possible? Or have to do it some other way?
If I understand correctly, you want not exists:
select l.*
from logging l
where not exists (select 1
from events e
where e.eventtime >= l.fromtime and
e.eventtime <= l.totime
);
However, this returns two timeframes -- ones with ids 3 and 4.
Here is a db<>fiddle.

Excluding rows from second table but including in comparison

I have two tables with the same data in it I need to compare one column here is the ddl for testing
USE [DifferencesDB]
GO
/****** Object: Table [dbo].[FirstTable] Script Date: 11/06/2019 15:27:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FirstTable](
[Id] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Column4] [decimal](18, 0) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[FirstTable] ([Id], [Column1], [Column2], [Column4]) VALUES (1, N'test ', N'test ', 30)
GO
INSERT [dbo].[FirstTable] ([Id], [Column1], [Column2], [Column4]) VALUES (2, N'test2 ', N'test3 ', 18)
GO
CREATE TABLE [dbo].[SecondTable](
[Id] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Column4] [decimal](18, 5) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[SecondTable] ([Id], [Column1], [Column2], [Column4]) VALUES (1, N'test ', N'test ', 13.56895)
GO
INSERT [dbo].[SecondTable] ([Id], [Column1], [Column2], [Column4]) VALUES (2, N'test2 ', N'test3 ', 18.456 )
GO
As you can see here what I want to do is compare to the two tables and the Data in Column 4 which is a decimal.
/****** Script for SelectTopNRows command from SSMS ******/
SELECT ABS(T0.Column4 -T1.Column4) as 'Difference'
FROM [FirstTable] T0, [SecondTable] T1
where T0.Id =T1.ID
This works but it gives me back tones of extra rows this gets me the difference I require so how do I exclude the rows from the other table.
So, for example, it should say the difference is I would like the data to be returned from the second table but also the difference column as well.
.456
Edit
TO show what is happening on live data.
Please see my new query here
SELECT GoodData_Lines.Qty,
Invalid_Lines.Qty,
abs(GoodData_Lines.Qty- Invalid_Lines.Qty) AS 'Difference'
FROM GoodData_Lines
left OUTER JOIN Invalid_MCSSOPLines
ON GoodData_Lines.LineID = Invalid_Lines.LineID
Not exactly sure what the question was, but based on how I understand it, will this do?
SELECT T1.*, ABS(T0.Column4 -T1.Column4) as 'Difference'
FROM [FirstTable] T0 right join [SecondTable] T1
on T0.Id =T1.ID
This can be a solution?
[EDIT] following your update
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[GoodData_Lines](
[LineID] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Qty] [decimal](18, 0) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[GoodData_Lines] ([LineID], [Column1], [Column2], [Qty]) VALUES (1, N'test ', N'test ', 30)
GO
INSERT [dbo].[GoodData_Lines] ([LineID], [Column1], [Column2], [Qty]) VALUES (2, N'test2 ', N'test3 ', 18)
GO
CREATE TABLE [dbo].[Invalid_MCSSOPLines](
[LineID] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Qty] [decimal](18, 5) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Invalid_MCSSOPLines] ([LineID], [Column1], [Column2], [Qty]) VALUES (1, N'test ', N'test ', 13.56895)
GO
INSERT [dbo].[Invalid_MCSSOPLines] ([LineID], [Column1], [Column2], [Qty]) VALUES (2, N'test2 ', N'test3 ', 18.456 )
GO
SELECT GoodData_Lines.Qty,
isnull( [Invalid_MCSSOPLines].Qty,0) invalid_qty,
abs(GoodData_Lines.Qty - isnull([Invalid_MCSSOPLines].Qty,0)) AS 'Difference'
FROM GoodData_Lines
left OUTER JOIN Invalid_MCSSOPLines
ON GoodData_Lines.LineID = [Invalid_MCSSOPLines].LineID
-- eventually drop table if no more needed
-- DROP TABLE [GoodData_Lines]
-- DROP TABLE [Invalid_MCSSOPLines]

how to get table from first table when data is not there in second table

i have requirement where i need to show data of both tables when both the ID's are same.when id is present in first table and not there in second table i need to show data from first table
CREATE TABLE [dbo].[TEST](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Test_History](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Test_History] Script Date: 06/19/2015 19:01:49 ******/
INSERT [dbo].[Test_History] ([ID], [Name], [Status], [CreatedDate]) VALUES (1, N'Mohan', N'A', CAST(0x0000A4BC01347E88 AS DateTime))
INSERT [dbo].[Test_History] ([ID], [Name], [Status], [CreatedDate]) VALUES (1, N'Mohan', N'I', CAST(0x0000A4BC0134A390 AS DateTime))
INSERT [dbo].[Test_History] ([ID], [Name], [Status], [CreatedDate]) VALUES (2, N'Rohan', N'A', CAST(0x0000A4BC01391FCC AS DateTime))
/****** Object: Table [dbo].[TEST] Script Date: 06/19/2015 19:01:49 ******/
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (2, N'Rohan', N'I', CAST(0x0000A4BC0138D584 AS DateTime))
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (1, N'Mohan', N'A', CAST(0x0000A4BC013072DC AS DateTime))
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (3, N'Raj', N'A', CAST(0x0000A4BC0138DED7 AS DateTime))
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (4, N'Krishna', N'A', CAST(0x0000A4BC0138EE31 AS DateTime))
so far i have tried my query to achieve the result
select T.ID,COALESCE(T.ID,TT.ID),T.Name,COALESCE(T.Name,TT.Name),T.status,COALESCE(T.status,TT.status)
from Test T LEFT JOIN (Select TOP 1 ID,MIN(Name)name,Status from Test_History
GROUP BY ID,status
)TT
ON T.ID = TT.ID
where T.ID = 3
Id = 1 and 2 present show i will get data from both tables
Id = 3 and 4 not present in the table
so using coalesce i will get the data
from first table and show in 2nd table column also
but is there any other way like both tables are same structure
i'm thinking of
Declare #tablename varchar(10)
IF EXISTS (SELECT 1 from TESt where id = #id)
IF COunt there in both tables
SET #tablename = Test
ELSE
SET #tablename = Test_history
select * from #tablename where id = #ID
can i get any solution like this
You can use EXCEPT.
Here is an example:
SELECT a,b
FROM (
VALUES (1, 2), (3, 4), (5, 6), (7, 8), (9, 10)
) AS MyTable(a, b)
EXCEPT
SELECT a,b
FROM (
VALUES (1, 2), (7, 8), (9, 10)
) AS MyTable(a, b);
This will return all rows of the upper statement, which are not in the second statement.
First: Thanks for the excellent setup for the data related to the question!
If your real question was if table variables can be used as described in your question, the answer is no; or more accurately that its not worth it.
Not recommended:
declare #TableName TABLE (
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL)
IF EXISTS (SELECT 1 from TESt where id = #id)
INSERT INTO #TableName SELECT * FROM dbo.TEST WHERE ID = #ID
ELSE INSERT INTO #TableName SELECT * FROM dbo.[Test_History] WHERE ID = #ID
select * from #tablename where id = #ID
Here's the solution I prefer:
DECLARE #ID INT = 3;
SELECT * FROM [dbo].[TEST] ss WHERE ss.id = #id
UNION ALL SELECT * FROM [dbo].[Test_History] th WHERE th.id = #id
and not exists ( SELECT * FROM [dbo].[TEST] ss WHERE ss.id = #id);
UNION ALL performs surprisingly well - don't forget the ALL keyword, and I am assuming that ID is a PK or AK.
If I'm understanding correctly and you want to display all records that match between the two tables and only records from first table when the id does not exist in the second in the same result set, then all you need is a simple left join:
SELECT *
FROM dbo.test t
LEFT OUTER JOIN Test_History th
ON t.id = th.id
WHERE t.id = #id