Select Column is its contain value SQL Server - sql

I have one Audit Table which have Multiple Column,
Lets Say
Create table TestTable ( ID int, Col1 varchar(10), Col2 varchar(10), Col3 varchar(10), Col4 varchar(10), Col5 varchar(10), Col6 varchar(10), Col7 varchar(10));
insert into TestTable values(1,'Ram',null,null,null,null,null,null);
insert into TestTable values(2,null,1,null,'2',null,null,null);
insert into TestTable values(3,null,1,null,'2',null,null,null);
Now I want IF User run below Query
Select *[]* From TestTable where ID=1
Then Output should come like this.
**ID Col1
1 Ram**
and User run below query
Select *[]* From TestTable where ID=2
Then Output should come like this.
**ID Col2 Col4
1 1 2
Column is should not be static, If have value in row that column should come.
Any Idea how to get that results, I need to select the columns dynamically.

It is not impossible to do, but the query to generate that kind of result would be complex and require dynamic generation of the SQL statement.
Filtering which columns should be displayed should rather be the job of your frontend. It would also be hard for any other system to rely on a result set with a dynamic number of column.

Related

Insert into a table with the data present in one table which match the first row of another table

I am new to sql.
I want to insert a data to backup table from main table that also matches the first record of another table.
suppose I have backup table with name "baktble" and main table with name "sales".
note : both tables have same columns c1,c2,c3,c4,c5,c6.
and I have a buffer table "buftble" with columns only the first 3 columns of bakup and sales table c1,c2,c3.
Now how to insert a data into backup table from sales table which matches the columns of first record.
I tired this but got error.
insert into baktble
select *
from sales
where col1,col2,col3 in (
select top 1 col1,col2,col3
from buftble).
So while nbk's as is the correct SQL syntax for your query:
create table baktble(col1 int, col2 int, col3 int, col4 int, col5 int, col6 int);
create or replace table sales(col1 int, col2 int, col3 int, col4 int, col5 int, col6 int);
create or replace table buftble(col1 int, col2 int, col3 int);
insert into buftble values
(1,10,100),
(2,20,200),
(3,30,300);
insert into sales values
(1,10,100, 101, 102, 103),
(2,20,200, 201, 202, 203),
(3,30,300, 301, 302, 303);
insert into baktble
select *
from sales
where (col1,col2,col3) in (
select top 1 col1,col2,col3
from buftble);
this only ever inserts zero or one row from sales into baktble.
Because the top 1 only selects one row from buftble
If I had to guess what you are wanting to do is ether:
insert all sales that match the distinct rows in buftble
insert the first sales row that matches the distinct rows in buftble
The first is done with:
insert into baktble
select *
from sales
where (col1,col2,col3) in (
select distinct col1,col2,col3
from buftble);
and the later (with the assumption that col4 is valid to sort duplicate values by) using QUALIFY and ROW_NUMBER like so:
insert into baktble
select *
from sales
where (col1,col2,col3) in (
select distinct col1,col2,col3
from buftble)
qualify row_number() over (partition by col1,col2,col3 order by col4 desc) = 1;

"Batch auto-increment" IDs for multiple row insertion

I am working in SQL Server 2017, and I have a table of the form:
tbl_current
COL1 COL2
-----------
A 1
B 3
C 56
which I want to periodically insert into the table tbl_release.
This table would have an extra ID column, which I'd like to auto-increment with each "batch insertion". For example, let's say I perform the the ingestion of tbl_current into tbl_release, it would look like this:
tbl_release
ID COL1 COL2
----------------
1 A 1
1 B 3
1 C 56
Now, let's say I perform another ingestion with the same data, it'd look like:
tbl_release
ID COL1 COL2
----------------
1 A 1
1 B 3
1 C 56
2 A 1
2 B 3
2 C 56
What is the best way to achieve this? Is there some SQL Server feature that would allow to achieve this, or do I need to run some sub-queries?
I'd personallly use a sequence for this. Assuming the insert into your ephemeral table is done, it'd looks omething like this:
declare #ID int = next value for sequence dbo.mySequence;
insert into tbl_release
(ID, col1, col2)
select #ID, col1, col2
from tbl_current;
You can try this using MAX() function as shown below.
Declare #maxId int
set #maxId = (Select isnull(id, 0) from tbl_Current)
set #maxId = #maxId + 1
--Now to insert
insert into tbl_release values (#maxId, <Column1Value>, <Column2Value>)
For multiple insert you can try this
INSERT INTO tbl_release
SELECT #maxId, col1, col2 FROM tbl_Current
If your table's Id column is identity then you can also use the Scope_Identity to get the max value of Id column.
Your id is really an object. I would strongly suggest that you give it a full table:
create table batches (
batch_id int identity(1, 1) primary key,
batch_start_date datetime,
. . .
);
Then, your existing table should be structured as:
create table releases (
release_id int identity(1, 1) primary key,
batch_id int not null references batches(batch_id),
col1 char(1),
col2 int
);
That way, your database has referential integrity.

Query for Merge values from 3 column and merge as Primary Key in Oracle

In one table few columns are there and in 3 columns i want to merge values from these 3 columns and generate as Primary key after merging these 3 values.
Col1 having Datatype length 4, While col2 & col3 having datatype length 5 & 3 respectively. In col2 & col3 if any values are less than the maximum length then use LPAD with 0 and then after Merge into the Primary Key.
Ex- If col1 = 1234, col2 = 142, col3 = 32 then after merging It should be like "123400142032" as Primary Key.
You probably need something like this.
CREATE TABLE yourtable
(
col1 NUMBER,
col2 NUMBER,
col3 NUMBER
);
ALTER TABLE yourtable ADD (ID NUMBER GENERATED ALWAYS AS ( LPAD(col1,4,0)||LPAD(col2,5,0)||LPAD(col3,3,0) ) );
ALTER TABLE yourtable ADD CONSTRAINT t_test_pk PRIMARY KEY (ID) USING INDEX;
You may then insert only 3 columns and the column id gets automatically populated with a number such as 123400142032.
INSERT INTO yourtable (col1, col2, col3)
VALUES (1234, 142, 32);
Note : The create table script is just for understanding. You may not need it since you already have an existing table.
The virtual column syntax GENERATED .. AS works only in 11g and above. For lower versions, you may require a before insert trigger and a sequence.
with lp as
(select max(length(employee_id)) mp from employee),
llp as
(select max(length(first_name)) mf from employee)
select lp.*,lpad(employee_id,lp.mp,'0'),llp.*, lpad(first_name,llp.mf,'0'),
employee_id||lpad(employee_id,lp.mp,'0')||lpad(first_name,llp.mf,'0')from lp,llp,employee;
note: here employee_id and first_name are the columns, you can assume it as column1 and column2..

In SQL,How to pick columns which doesnt have 0 value?

I have pivot query which will result one row of record. I will have to further filter that one row of record. One row of record has hour based columns and so, i have 24 columns for each hour.
How to pick columns which has only values
Lets say we have 5 columns
Col1 Col2 Col3 Col4 Col5
100 0 0 20 0
Col1, Col4 are eligible. I need total these two columns.
Col1 Col4 Total
100 20 120
create table #t
(
Col0 int,
Col1 int,
Col2 int,
Col3 int,
Col4 int,
Col5 int,
Col6 int,
Col7 int,
Col8 int,
Col9 int,
Col10 int,
Col11 int
)
insert into #t values
(0,100,0,0,0,0,20,10,0,0,0,0)
select * from #t
-- Expected Result
select Col1, Col6, Col7 from #t
You can not do that using a static pivot table, dynamic perhaps. It is not known when a pivot table is defined if all the values are null or not and by the time the data is piped in it is too late. You can either create a reporting project that supports omitting empty column groups or look for a more dynamic query alternative.

SQL-Multiple Insert into identity table

I need to to do a insert from a table with the following structure:
Table A
Col1 Col2 Col3 Col4
intID1 intID2 intID3 intID4
I need to select the rows from the above table that are null
for col1,col2,col3 and insert those rows into a table that will generate an identity
row that I need to use to insert into another table.I am not sure of the
sql statement or the general method used to select those rows and insert them multiple times and retrieve the identity id one by one to insert into the next table.
Any help is greatly appreciated!
Sample process:
Table A
Col1 Col2 Col3 Col4
1 3 7 null
null null null 45
null null null 67
1)Retrieve rows 2 and 3
2)Insert 2 and 3 into another table to retrieve identity id for both rows
3)Insert identities from step 2 into another table
Venk covered step 1 and 2 I think. For 3 can use the OUPUT clause to retrieve the identity value from set operation.
Get Identity of multiple insertion in sql server 2008
INSERT INTO TABLEB(Col1,Col2,Col3,Col4)
SELECT * FROM TABLEA WHERE Col1 is NULL AND Col2 is NULL AND Col3 is NULL;
Sounds like you need the output operator:
declare #TableA table(Col1 int, Col2 int, Col3 int, Col4 int);
declare #TableB table(id int identity(1,1), Col1 int, Col2 int, Col3 int, Col4 int);
declare #Audit table(id int);
insert into #TableA
select 1,3,7,null union all
select null, null, null, 45 union all
select null, null, null, 67;
-- copy null columns from #TableA to #TableB
-- and output id's to #Audit
insert into #TableB
output inserted.id
into #Audit
select *
from #TableA
where Col1 is null
and Col2 is null
and Col3 is null;
-- Copied #TableB values and #Audit values
select * from #TableB;
select * from #Audit;