return the column name from dynamic string - sql

I want to get the column from the dynamic string, In my table: MyTable2 I have many columns/fields, which are :
MyVarCharColumnName1,MyVarCharColumnName2,MyVarCharColumnName3,MyVarCharColumnName4
These above fields are nvarchar(50),
I wonder how I can get the value of them when join with another table as below example:
SELECT
*,
CASE
WHEN Tbl1.MyId IN ('1', '2', '3', '4')
THEN (SELECT 'MyVarCharColumnName' + bf.MyId
FROM MyTable2)
ELSE Tbl1.MyId
END AS TheNameofId
FROM
Tbl1
above is wrong because it will return MyVarCharColumnName1 as TheNameofId value instead of the value inside MyVarCharColumnName1
Is there are some sql function that can return the column name from a string?
any way to convert 'MyVarCharColumnName1' to column object?

As it is confirmed that you have to write dynamic query to do in the same way as you are asking but beside that we can do the same in the following way using CASE
SELECT
*,
CASE
WHEN Tbl1.MyId = 1 THEN MyVarCharColumnName1
WHEN Tbl1.MyId = 2 THEN MyVarCharColumnName2
WHEN Tbl1.MyId = 3 THEN MyVarCharColumnName3
WHEN Tbl1.MyId = 4 THEN MyVarCharColumnName4
ELSE Tbl1.MyId
END AS TheNameofId
FROM Tbl1

Related

Where condition with integer values return same as ir were a string

These two queries in SparkSQL return the same value and I don't know why.
Treating the condition attribute as integer or string.
select count(*) from <my_table> where <my_column> = 100
union all
select count(*) from <my_table> where <my_column> = '100'
In Logical plan it cast string values to int values based on schema refer this to understand more - https://medium.com/datalex/sparks-logical-and-physical-plans-when-why-how-and-beyond-8cd1947b605a
where column = 0 ............................................and where column = '0'

How to loop through one table and then Insert into another based on multiple IF ELSE

I have a table like below with 2 columns. This table already is populated with all the data I need.
Table 1
ID (int) TYPE (string)
The other table looks like this and it's empty
Table 2
ID (int) Somedetail (int)
I need to loop through Table 1 and then insert into Table 2 if TYPE = 'string'
for each row and I have about 5 different string I need to test against.
INSERT WILL BE insert into Table 2 (ID, int). I will provide the int value based on if TYPE = 'string' matches or not.
This is what I have currently.
SELECT ID, TYPE
FROM TABLE1
IF(ID = 'STRING1')
INSERT INTO TABLE2...
ELSE IF (ID = 'STRING2')
INSERT INTO
and so on
You are basically looking for an INSERT INTO SELECT statement (https://learn.microsoft.com/en-us/sql/t-sql/statements/insert-transact-sql). In your case this would take the form:
INSERT INTO Table2
SELECT
id,
CASE
WHEN type = 'string1' THEN intvalue1
WHEN type = 'string2' THEN intvalue2
WHEN type = 'string3' THEN intvalue3
WHEN type = 'string4' THEN intvalue4
WHEN type = 'string5' THEN intvalue5
END
FROM Table1
WHERE type IN ('string1', 'string2', 'string3', 'string4', 'string5');
Where we just take the results of that SELECT statement and shove it into Table2 with the INSERT INTO.
Fairly positive you want to use CASE based on your comments. You'll have to fill in the strings and the ints that you want, but here is the shell:
INSERT INTO Table2 (ID, Somedetail)
SELECT ID,
CASE WHEN Type = 'string1' THEN 1,
WHEN Type = 'string2' THEN 2,
etc...
END as Somedetail
FROM Table1

Search SQL and return true or false

I have a table that has thousands of rows in. I need to check if certain values exists in the table or not.
I want to list all the bar codes I am searching with a flag of true or false returned if there is one.
I have come up with this so far:
SELECT CASE WHEN EXISTS (
SELECT *
FROM TABLE
WHERE Coulmn in ('a','b', 'c', 'd', 'e', 'f', 'g')
)
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END
This however just returns a value of 1.
So in the table I have
coulmn
----------
A
B
D
E
F
G
I want to do a search that returns the following
Coulmn | Exsists
-----------------
A | True
B | True
C | False
D | True
E | True
F | True
G | True
You can use a query like the following:
SELECT t1.v,
CASE WHEN t2.col IS NOT NULL THEN 'true' ELSE 'false' END AS Exists
FROM (
SELECT 'a' AS v UNION ALL SELECT 'b' UNION ALL SELECT 'c' UNION ALL SELECT 'd'
UNION ALL SELECT 'e' UNION ALL SELECT 'f' UNION ALL SELECT 'g') AS t1
LEFT JOIN mytable AS t2 ON t1.v = t2.col
This works:
SELECT *, CASE WHEN (Column in ('1','2')) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS result_field
FROM TABLE;
NOTE: Tested in PostgreSQL
As it's written, the outer select is select case when exists () then 1 else 0 end... so it is only going to return one row. The outer select must include "Column" AND "Exists" (select column, ...) to return two columns.
A "where" clause will never return a "false" like this, though, because "column" has to be in a real table for the query to actually return it. As #jarlh says, you'll need a helper table to store the columns you're looking for:
Create table SearchColumns (SearchColumn char(1));
insert into SearchColumns (SearchColumn)
values ('A'), ('B'), ('C'), ('D'), ('E'), ('F'), ('G'), ('H')
Then you can do the If Exists to your table from that table to see which values are in or not in:
select SearchColumn, case when exists
(select * from TABLE where Table.Column = SearchColumns.SearchColumn)
then 'True' else 'False' end as ExistsStatus
from SearchColumns
I think that will get you what you want. This gets a) Only one record per column no matter how many times it occurs in your table and b) "True" and "False" for every column value you're looking for. If you really wanted a Bit, you can use 0 and 1 and the casting from the original query, but they actually show "0" and "1"; and c) this should work no matter how many values you have.
(Note, I assumed some of those were spelling errors, so I made adjustments, but they were consistent so I'm not certain).
With the help form above I created a temp table and then implemented one of the soultions shared.
CREATE TABLE #Temp
(
Barcode VARCHAR (100)
)
INSERT INTO #Temp
VALUES
(1),
(2),
(3),
(4 )
select barcode, case when exists
(select * from CIPKORHHTProductDetails where CIPKORHHTProductDetails.Barcode = #temp.barcode)
then 'True' else 'False' end as ExistsStatus
from #temp order by ExistsStatus DESC

SQL CASE SUBQUERY COUNT

I have table with 2 col :
UID NAME
-----------
111 AAA
222 BBB
Customer will enter the name and I have to retrieve UID with respective value. If name won't present in the rows, it has to retrieve 000, not like no rows.
I am trying to write query like this:
SELECT
CASE UID
WHEN Count(*) = 0 THEN '000'
ELSE UID
END
FROM table1
WHERE NAME ='XXX'
Please help me in this regard. Thanks in advance...
If UID is an integer, then you need to take casts into account:
select coalesce(cast(max(uid) as char(3)), '000')
from table1
where name = 'XXX'
The cast is intended to be to the type of UID, which seems to be char(3) in your example.
When there are no matching rows, then the max() function returns NULL. The coalesce() turns this into the value you are looking for.
try this
select case
when max(id) is null then
0
else
max(id)
end
from table1
where name = 'b'
You have error in case
SELECT case when count(UID) = 0 THEN '000' ELSE UID end FROM table1 where name = 'XXX'
sqlfiddle :http://www.sqlfiddle.com/#!2/257ea/1

Referring to results of a sub query in main query

I have a sub query that returns one column, showing as GroupType, I then want to do a CASE function on this result within the main query, however I get an invalid column name when using the CASE statement.
Can i do this in SQL to do I have to refer to it by a different name
SELECT CASE
WHEN
(
SELECT column
FROM othertable
) = 1
THEN '1'
ELSE '2'
END
FROM mytable
To reuse the subquery result:
SELECT subvalue, CASE subvalue WHEN 1 THEN 1 ELSE 2 END
FROM (
SELECT (
SELECT column
FROM othertable
) AS subvalue
FROM mytable
) q