SQl select specific column but with use of * - sql

I need help, my SQL Server select statement is:
select * from schematemplate.scanner
the columns of this table are:
id
Asset_Category
Asset_Classification
Brand
Model
Supplier
Color
I can select all the columns except the Asset_Category and Asset_Classification by using this:
Select id, brand, model, supplier, color
from schematemplate.scanner
But I don't want to specify the columns that I will select like the code above.
Is it possible to use SELECT * from schematemplate.scanner and add a code like EXCEPT asset_category and asaset_classification?

Those are only five columns. Why not select it?
Anyway, here's a suggestion that you may take,
create a view and
run select on it,
example
CREATE VIEW viewScanner
AS
SELECT id, brand, model, supplier, color
FROM schematemplate.scanner
and when you want to select records,
SELECT * FROM viewScanner

You could do it dynamically, e.g.:
declare #s varchar(max) = 'select '
select #s=#s+name+',' from sys.columns
where object_id=object_id('schematemplate.scanner')
and name not in ('asset_category','asset_classification')
order by column_id
set #s=substring(#s,1,len(#s)-1)+' from schematemplate.scanner'
exec(#s)
sqlfiddle

Related

Use a select query result in an other query

Could please someone explain, how to use a result from a SELECT (1st select result)
Then use that result (1st select result) on a second query VALUES clause
there is an example (on Microsoft SQL Server) :
--1st query, select all DB1.client.name
select Name from DB1.client
--the result of that query is : 1st select result VALUES : ana,boby, ..., micky
--2nd query, compare DB1.client.name (1st select result) with DB2.client.name
--and get back who doesn't exist on second table
select v.Name
from (values
**(There i want use the result of my first query)**
) as v(Name)
where not exists (select *
from DB2.client c
where c.Name = v.Name);
--the result is ana, ..., micky
"..." mean some other results
i want compare first and second database to retrieve values which aren't in both databases
If you can, I recommend sub-query :
select Name
from DB1.client
where Name not in not exists (select name from DB2.client)
If you want reuse a query (not the result), see #Thkas answer.
It isn't possible to reuse the result in SQL Server, because SQL Server release the memory when the result is read. The trick is to insert the query's result in a temporary table, then you read this temporary table as many times as necessary :
--Insert into temporary table
insert into #tmpResult
select Name from DB1.client
--First read
select Name from #tmpResult
--Second read from sub-query
select Name
from #tmpResult
where Name not in not exists (select name from DB2.client)
According to your sample code I understood something like this. You can add two tables and do with WHERE the check you want.
select a.Name,b.Name
from DB1.client,
DB2.client as b
where a.Name != b.Name;
Also if you want to take as a result set from the first query:
Here I created a subquery which takes the results from the first query. You can correct me for columns.
with temp as (
select Name
from DB1.client
)select a.Name,b.Name
from temp as a ,
DB2.client as b
where a.Name != b.Name;

SELECT * FROM (SELECT)

There is a table "MAIN_TABLE" with columns "Table_Unique_Code" and "Table_name".
Also there are several tables with required data.
The task is to create SQL-query with parameter ("Table_Unique_Code"), which will select all data from the table determined by the "Table_Unique_code".
Something like
SELECT * FROM (*determine the name of the table by Table_Unique_code here*);
I tried
SELECT * FROM (SELECT table_name FROM MAIN_TABLE WHERE Table_Unique_Code=?)
but it doesn't work.
I work with OracleDB.

SQL Finding data from similar tables

I have a 50 tables with similar structures with name TABLE_1, TABLE_2, TABLE_3 etc. I want to select some information like SELECT * FROM TABLE WHERE CRM_ID = 100 but I dont know which table consists this ID. I guess that I should make a union with this tables and make a query from this union but I am afraid that it is not the best solution. Could anybody help me?
To find the table containing the field CRM_ID, you can use:
select TABLE_NAME
from SYS.ALL_TAB_COLUMNS
where COLUMN_NAME = 'CRM_ID'
From here, you can query the relevant tables with your union
select 'table_1', count(*) from table_1 where CMR_ID = 100
union all
select 'table_2', count(*) from table_2 where CMR_ID = 100
[.....]
If you have 50 tables, you may want to use some advanced text editing so you don't have to type the same line 50 times.
I can't see anything different from a UNION to get what you need.
However, I would like to avoid repeating all the code every time you need to query your tables, for example by creating a view:
create view all_my_tables as
select * from table1
union
select * from table2
...
and then
select *
from all_my_tables
where crm_id = 100
I would
create a view table_all as
select * from table_1 union all
select * from table_2 ...
but I guess you have 50 tables due to some performance reason like creating partitioning without partitioned table. If that is the case you need some table that simulates index and you need to have data "sorted". Then create table that contains: table_name, min_val, max_val:
table_1, 1, 1000
table_2, 1001, 2000
and procedure selecting looks like:
procedure sel(crmid) is
a varchar2(10);
value table%rowtype;
begin
select table_name into a from lookup where crmid between min_val and max_val;
execute immediate 'select * from ' || a || ' where crm_id = ' || crmid into value;
--do logic with value
end;
but if data is not ordered you need to iterate selects in loop. In such case use view.
Try this:
Select tmp.tablename from (
select 'table1' as tablename from table1 where CRM_ID=100
union all
select 'table2' as tablename from table2 where CRM_ID=100
) as tmp

Converting a pivot table to a flat table in SQL

I would like to transform a pivot table into a flat table, but in the following fashion: consider the simple example of this table:
As you can see, for each item - Address or Income -, we have a column for old values, and a column for new (updated values). I would like to convert the table to a "flat" table, looking like:
Is there an easy way of doing that?
Thank you for your help!
In order to get the result, you will need to UNPIVOT the data. When you unpivot you convert the multiple columns into multiple rows, in doing so the datatypes of the data must be the same.
I would use CROSS APPLY to unpivot the columns in pairs:
select t.employee_id,
t.employee_name,
c.data,
c.old,
c.new
from yourtable t
cross apply
(
values
('Address', Address_Old, Address_new),
('Income', cast(income_old as varchar(15)), cast(income_new as varchar(15)))
) c (data, old, new);
See SQL Fiddle with demo. As you can see this uses a cast on the income columns because I am guessing it is a different datatype from the address. Since the final result will have these values in the same column the data must be of the same type.
This can also be written using CROSS APPLY with UNION ALL:
select t.employee_id,
t.employee_name,
c.data,
c.old,
c.new
from yourtable t
cross apply
(
select 'Address', Address_Old, Address_new union all
select 'Income', cast(income_old as varchar(15)), cast(income_new as varchar(15))
) c (data, old, new)
See Demo
select employee_id,employee_name,data,old,new
from (
select employee_id,employee_name,adress_old as old,adress_new as new,'ADRESS' as data
from employe
union
select employee_id,employee_name,income_old,income_new,'INCOME'
from employe
) data
order by employee_id,data
see this fiddle demo : http://sqlfiddle.com/#!2/64344/7/0

Select rows from SQL where column doesn't match something in a string array?

Let's say I have a table, Product, with a column called ProductName, with values like:
Lawnmower
Weedwacker
Backhoe
Gas Can
Batmobile
Now, I have a list, in Notepad, of products that should be excluded from the result set, i.e.:
Lawnmower
Weedwacker
Batmobile
In my real-life problem, there are tens of thousands of records, and thousands of exclusions. In SQL Studio Manager, how can I construct a query similar to the following pseudocode that will just return Backhoe and Gas Can as results?:
declare #excludedProductNames varchar(MAX) =
'Lawnmower
Weedwacker
Batmobile'
SELECT ProductName FROM Product
WHERE ProductName isn't in the list of #excludedProductNames
This is just a one-time report, so I don't care about performance at all.
First thing is getting those words into SSMS - you can construct a derived table using UNION ALL:
SELECT 'Lawnmower' AS word
UNION ALL
SELECT 'Weedwacker'
UNION ALL
SELECT 'Batmobile'
This will return a table with a single column, named "word":
word
--------
Lawnmower
Weedwacker
Batmobile
Caveat
You'll need to escape any single quotes in your data. IE: O'Brian needs to be changed to O''Brian--just double up the single quote to escape it.
Now, to the real query...
Using NOT IN
Some databases limit the number of clauses in the IN, somewhere in the thousands IIRC so NOT EXISTS or LEFT JOIN/IS NULL might be better alternatives.
SELECT p.*
FROM PRODUCT p
WHERE p.productname NOT IN (SELECT 'Lawnmower' AS word
UNION ALL
SELECT 'Weedwacker'
UNION ALL
SELECT 'Batmobile'
...)
Using NOT EXISTS
SELECT p.*
FROM PRODUCT p
WHERE NOT EXISTS (SELECT NULL
FROM (SELECT 'Lawnmower' AS word
UNION ALL
SELECT 'Weedwacker'
UNION ALL
SELECT 'Batmobile'
...) x
WHERE x.word = p.productname)
Using LEFT JOIN/IS NULL
SELECT p.*
FROM PRODUCT p
LEFT JOIN (SELECT 'Lawnmower' AS word
UNION ALL
SELECT 'Weedwacker'
UNION ALL
SELECT 'Batmobile'
...) x ON x.word = p.productname
WHERE x.word IS NULL
Which is The Most Efficient/Fastest?
If the columns compared are not nullable, NOT IN or NOT EXIST are the best choice.
i think you're best to use some text editor tricks to accomplish this. replace newlines with ', ' for example, and you can easily go for a select * from product where ProductName not in ('...', '...') query.
Create a temp table, load all your exclusions there and select all rows that do not exist in the temp table.
-- create temp table #exclusions
select ProductName into #exclusions
from Product
where 1 = 2
# run a bunch of inserts
insert into #exclusions (ProductName) values ('LawnMower')
-- as many as needed...
# run your select
select * from Product
where ProductName not in (select Product from #exclusions)
drop table #exclusions
As an alternative to running a ton of inserts, use bcp to upload a csv file containing the ProductNames into a non temp table.