Create and use column in create statement same time of table - sql

I want to create a table with fetch the data from source table.
I can do it using alter and update function but I don't want to do it that way.
I have to create two columns and use 1 column(c1) in other as case statement in second(c2) column.
insert into table t
(select
a,b, case when d>f then 1 else 0 end as c1,
case when c1=1 then "yes" else null end as c2,
from base_temp
where a>b
)

If the question is on how to create a table and populate it with the results of some SELECT statement, then look at the CREATE TABLE as-result-table syntax.
You may use AS (full-select) WITH DATA syntax to create a new table with metadata based on the query provided and insert the result of this query into this table at the same time.
If the question is on how to use column aliases in expressions, then refer to the Expressions refer to column aliases topic.
You must have the SQL_COMPAT global variable set to the 'NPS' value in your session to make it work.
You may set it with the SET SQL_COMPAT = 'NPS' statement before running the corresponding SELECT statement.
SET SQL_COMPAT='NPS';
SELECT
TABSCHEMA, TABNAME
, CASE WHEN COLCOUNT > 20 THEN 1 ELSE 0 END AS C1
, CASE WHEN C1 = 1 THEN 'YES' ELSE NULL END AS C2
FROM SYSCAT.TABLES
FETCH FIRST 5 ROWS ONLY;
If you can't or don't want to set this variable, you may use sub-select to achieve the same:
SELECT
TABSCHEMA, TABNAME
, C1
, CASE WHEN C1 = 1 THEN 'YES' ELSE NULL END AS C2
FROM
(
SELECT
TABSCHEMA, TABNAME
, CASE WHEN COLCOUNT > 20 THEN 1 ELSE 0 END AS C1
FROM SYSCAT.TABLES
FETCH FIRST 5 ROWS ONLY
);

Related

Comparing two column values in postgres

I have table having following columns and records. I need to compare the two column values(ColumnA and ColumnB), if ColumnB>ColumnA then and update the third column from 'N' TO 'Y'
CREATE TABLE Test(ColumnA int,ColumnB int,Result Varchar(2))
INSERT INTO Test values(1,3,'N')
INSERT INTO Test values(2,1,'N')
INSERT INTO Test values(1,5,'N')
INSERT INTO Test values(8,7,'N')
I need to update Result Column='Y' for first and third row because columnB>ColumnA
Result
ColumnA ColumnB Result
1 3 Y
2 1 N
1 5 Y
8 7 N
This can be done with a simple CASE expression:
update test
set result = case
when columna > columnb then 'Y'
else 'N'
end
;
Online example: https://rextester.com/ZHIUZD82060
I would recommend to use a boolean column instead of a varchar to store "yes/no" flags. Then the update becomes as simple as set result = column_a > columnb
update test
set result =
case
when columnb > columna then 'Y'
else 'N'
end;
Hope this will help.

SQL if column is empty, add an empty column

I want to be able to check if we have a column and if not, then we just want to add an empty column,
IF Users.[parties] = '' OR NULL
BEGIN
SELECT [parties]
FROM Users
UNION
SELECT 'Empty'
END
The Users.[parties], we check to see if we have a column but if we don't, it will result in a crash, in the case for this event I thought it would be best just to add an empty column with the name of Empty but I can't get the code to work above.
If we do have columns, the results will be something like...
ColumnsName ColumnAge
data 33
data 22
But when there isn't a column, it crashes and ideally I would like it to just have an empty column like this,
EmptyColumn
The code below checks whether a column exists in the table, in our case the name of the column is columnName and the name of the table is tableName.
IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
-- Column exists
SELECT [parties] FROM Users
END
ELSE
BEGIN
-- Column does not exists
SELECT 'Empty'[parties]
END
I think you just want
IF EXISTS(
SELECT 1
FROM Sys.Columns
WHERE Name = N'parties'
AND
Object_ID = Object_ID(N'SchemaName.Users')
)
BEGIN
SELECT parties
FROM Users;
END
ELSE
BEGIN
SELECT 'EmptyColumn' EmptyColumn -- or NULL EmptyColumn
FROM Users;
END
I'll try with this: (I'm not sure it works)
select case when ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) =0 --count rows
then 'empty' -- if 0 output empty
else parties end as parties --else ouputs the result
from your_table
This is a more 'standard' approach
CREATE VIEW user_filled as
SELECT [parties]
FROM Users
UNION
SELECT 'EMPTY'
and when you query it (if needed -> on count(*))
select count(*)
from user_filled
where parties <> 'EMPTY'
on join
select *
from user_filled join other_table
on (user_filled <> 'EMPTY and userfilled.key= other_table.key)
NOTE: put the clause into the ON so it's filtered out BEFORE the join is made

How to limit the columns of the select statement?

I have to create a new table and inside should be the columns I get from the CASE statement. I do not need the rest of the columns resulting from the select statement
for example:
CREATE TABLE test
AS (
SELECT a.id, ...
CASE WHEN a.id = 1 THEN 2
ELSE 0
END as LegalType
FROM table a, ...
WHERE ...);
now my question how can I select only the column LegalType from the CASE statement? I do not want to have column a.id
You can SELECT INTO
SELECT CASE WHEN a.id = 1 THEN 2 ELSE 0 END as LegalType
....
INTO test
FROM table a
WHERE 1=1);
This will create you a table based on the data returned in the SELECT. see https://msdn.microsoft.com/en-GB/library/ms188029.aspx

Transformation logic using SQL Server

I want to update a column. When the value is not in the list or in table or doesn't match, it will return "Not Account Related" and when the value is in the list, the row will become blank. So this is my query.
SELECT
CASE Project_Names
WHEN "List_Value_Name".[LK_ProjectNames] = "Project_Names".[1]
THEN ''
ELSE "Not Account Related"
END
FROM
[master].[dbo].[1]
Table is LK_ProjectNames with columns List_Value_Name & table 1 with column Project_Names.
If value in table 1 column Project_Names got in the table LK_ProjectNames column List_Value_Name, it will return blank. if not it will return Not Account Related
If you are storing project name in table1 in one row one project basis.
SELECT *,
CASE WHEN EXISTS(SELECT 1 FROM LK_ProjectNames l WHERE LTRIM(RTRIM(t.Project_Names)) =LTRIM(RTRIM(l.List_Value_Name)) ) THEN '' ELSE 'Not Account Related' END as RESULT
FROM table1 t
If you are storing project names as comma seperated in table1 .
SELECT *,
CASE WHEN EXISTS(SELECT 1 FROM LK_ProjectNames l WHERE LTRIM(RTRIM(t.Project_Names)) like '%'+LTRIM(RTRIM(l.List_Value_Name))+'%' ) THEN '' ELSE 'Not Account Related' END as RESULT
FROM table1 t

SQL Server query - loop question

I'm trying to create a query that would generate a cross-check table with about 40 custom columns that show Y or N. Right now I have
SELECT DISTINCT [Company],
[Option1],
[Option2],
[Option3],
CASE
WHEN [Table1].[ID1] IN (SELECT ID2 FROM Table2 WHERE Variable = 1 AND Bit = 1) THEN
'Y'
ELSE 'N'
END AS 'CustomColumn1:',
CASE
WHEN [Table1].[ID1] IN (SELECT ID2 FROM Table2 WHERE Variable = 2 AND Bit = 1) THEN
'Y'
ELSE 'N'
END AS 'CustomColumn1:',
CASE
WHEN [Table1].[ID1] IN (SELECT ID2 FROM Table2 WHERE Variable = 3 AND Bit = 1) THEN
'Y'
ELSE 'N'
END AS 'CustomColumn1:',
.............
-- REPEAT ANOTHER 40 times
FROM [Table1]
WHERE [Table1].[OtherCondition] = 'True'
ORDER BY [Company]
So my question is, how do I create a loop (while? for?) that will loop on variable and assign Y or N to the row based on the condition, rather than creating 40+ Case statements?
You couldn't use a loop, but you could create a stored procedure/function to perform the sub-select and case expression and call that 40 times.
Also, you could improve performance of the sub-select by changing it to
SELECT 1 FROM Table2 WHERE EXISTS [Table2].[ID2] = [Table1.ID1] AND Variable = 3 AND Bit = 1
A loop (that is, iterating through a cursor) works on rows, not columns. You will still have to have 40 expressions, one for each column, and the performance will be terrible.
Let SQL Server do its job. And do your bit by telling exactly what you need and creating proper indices. That is, replace
CASE WHEN [Table1].[ID1] IN (SELECT ID2 FROM Table2 WHERE Variable = 2 AND Bit = 1)
with
CASE WHEN EXISTS (SELECT 0 FROM Table2 WHERE ID2 = [Table1].[ID1] AND Variable = 2 AND Bit = 1)
If the output is so vastly different than the schema, there is a question as to whether the schema properly models the business requirements. That said, I would recommend just writing the SQL. You can simplify the SQL like so:
Select Company
, Option1, Option2, Option3
, Case When T2.Variable = 1 Then 'Y' Else 'N' End As CustomCol1
, Case When T2.Variable = 2 Then 'Y' Else 'N' End As CustomCol2
, Case When T2.Variable = 3 Then 'Y' Else 'N' End As CustomCol3
, Case When T2.Variable = 4 Then 'Y' Else 'N' End As CustomCol4
...
From Table1 As T1
Left Join Table2 As T2
On T2.ID2 = T1.ID
And T2.Bit = 1
Where T1.OtherCondition = 'True'
Group By T1.Company
Order By T1.Company
If you want to write something that can help you auto-gen those Case statements (and you are using SQL Server 2005+), you could do something like:
With Numbers As
(
Select 0 As Value
Union All
Select Value + 1
From Numbers
Where Value < 41
)
Select ', Case When T2.Variable = ' + Cast(N.Value As varchar(10)) + ' Then ''Y'' Else ''N'' End As CustomCol' + Cast(N.Value As varchar(10))
From Numbers As N
You would run the query and copy and paste the results into your procedure or code.
One way could have been to use Pivot statement, which is in MS SQL 2005+. But even in that you have to put 1 ... 40 hardcoded columns in pivot statement.
Other way i can think of is to create dynamic SQL, but it is not so much recommended, So what we can do is we can create a dynamic sql query by running a while loop on table and can create the big sql and then we can execute it by using sp_execute. So steps would be.
int #loopVar
SET #loopVar = 0
int #rowCount
varchar #SQL
SET #SQl = ''
Select #rowcount = Count(ID2) from Table2
WHILE(#loopVar <= #rowCount)
BEGIN
// create ur SQL here
END
sp_execute(#SQL)