assign only particular column values to a temp table from select query - sql

I am having below query that will return 6 columns and i want only assign particular column (converted_skus) results to temporary table and i need to do further processing on that column only ..
I am not sure how can i assign only particular column values to temporary table where as other columns are not needed for further processing
here is my query
SELEct distinct
clpAct.pk_cert,CCM.leg_sku_des,CCM.converted_sku_des,CCM.converted_skus,
esitrans.pk_cert,esitrans.part_id from Clp_Active clpAct
inner join transfertable esitrans
ON clpact.pk_cert = esitrans.pk_cert
INNER JOIN pass_conversion CCM
ON esitrans.part_id = CCM.part_number
where clpAct.subscription_key = #subKey
Would any one please help on this query that would be very grateful to me.
Many thanks in advance
I am using sql server as DB

if you don't need the other columns, then just select your required column only and insert it into the temp table. like this
create table #temp
(
converted_skus varchar(50)
)
insert into #temp
(
converted_skus
)
SELEct distinct
CCM.converted_skus
from Clp_Active clpAct
inner join transfertable esitrans
ON clpact.pk_cert = esitrans.pk_cert
INNER JOIN pass_conversion CCM
ON esitrans.part_id = CCM.part_number
where clpAct.subscription_key = #subKey
now you have only the required column and values in the temp table #temp

Related

How to loop statements in SQL Server

I am new to SQL Server, I am trying to do something as follows.
Sample code :
SELECT ITEM_ID
FROM 'TABLE_NAME_1'
WHERE ITEM_STATUS = 'ACTIVE'
SET #ITEM_PRICE = (SELECT PRICE
FROM 'TABLE_NAME_2'
WHERE 'PRODUCT_ID' = 'ITEM_ID')
INSERT INTO 'TABLE_NAME_3' (ITEM_ID, PRICE)
VALUES (#ITEM_ID, #ITEM_PRICE)
The first statement will return multiple rows of ITEM_ID
By using the ITEM_ID I need to select the ITEM_PRICE from another table using the second statement
By using the third statement, I need to insert the data into the third table
Here the first statement returns only one ITEM_ID, then everything is easy to do. I f it returns multiple rows how can I do all these processes for all the ITEM_ID which has returned by the first statement?
Actually, If the first statement returns 5 rows I need to loop 5 times.
Is it possible in SQL Server, if yes, please help me to do this
Question would be why not use a straight SQL
INSERT
INTO 'TABLE_NAME_3'
(ITEM_ID
,PRICE
)
SELECT ITEM_ID,ITEM_PRICE
FROM 'TABLE_NAME_1' A
JOIN 'TABLE_NAME_2' B
ON A.ITEM_ID=B.PRODUCT_ID
WHERE A.ITEM_STATUS = 'ACTIVE'
based on your question i have created sample code you can use only one query to insert multiple data if you want to insert common data between table 1 and table 2 then use inner join or left join will be fine.
Code
INSERT INTO 'TABLE_NAME_3' (ITEM_ID,PRICE)
SELECT T1.ITEM_ID , T2.PRICE
FROM 'TABLE_NAME_1' AS T1
INNER JOIN 'TABLE_NAME_2' AS T2 ON T2.PRODUCT_ID = T1.ITEM_ID
WHERE T1.ITEM_STATUS = 'ACTIVE'

How can I grab one column from a subquery and insert that column into another table where I can query off of those ID's in another data table?

Trying to explain this the best I can, I have a subquery which is looking for some document information in one table, I need to then use an INSERT INTO to ONLY take the document IDs that are returned and query them in a separate data table.
This is what Im working with right now
use DATABASE
Select * into #Audit
From [dbo].[workflow] A
Where object_id IN
(
Select DISTINCT ChangeHistory.document_id, ChangeHistory.account_number,
min(timestamp)
from [dbo].[xip_workflow] A
INNER JOIN (select B.*
from [dbo].[changehistory] B
where B.doc_status like ('New')
and user_login_name like ('System')
and button_push like (' ')
and B.account_number in ('11111111')
and B.work_queue_system_name in ('r_queue')
and B.document_type in ('A1','A2','A3')
and timestamp > '4/11/2017') ChangeHistory
ON ChangeHistory.[document_id] = A.[object_id]
group by document_id, ChangeHistory.account_number)

SQL IN Clause replacement Temp table

My query is :
Select *
from Person
where KV_CODE IN('','',''......1000 values here)
How to write this list of values in a temp table so that I can replace IN clause with a join to increase performance.
This list of values is coming on the basis of random selection by user and is stored in a Java collection.
Select * from Person P INNER JOIN #Temp T ON T.KV_CODE = P.KV_CODE
You can apply INNER JOIN on Temp Table similar to Normal Tables.
select *
from Person
where KV_CODE in (
select KV_CODE
from TempTable
)
This will compare the KV_CODE of Person to the KV_CODE of TempTable. If there are matches, it will intersect them, meaning your first select will print only those rows.
select *
from Person p
join TempTable tmp
on p.KV_CODE = tmp.KV_CODE
This will join the two tables and display the matching rows from both tables.
Unless your question is "how to populate a temporary table from a java collection"
Newer database solutions optimize this already. There is not much difference between IN clause and Join as optimizer figures out this aspect and execute query by appropriate path.
If you still wish, here is what you have to do.
if you are using Oracle,
you can create a session scope or transaction scope temporary table.
Insert data into this temporary table
Fire query like
SELECT *
FROM PERSONS T1,
TEMP_TABLE_NAME_HERE T2
WHERE T1.KV_CODE = T2.KV_CODE
However, a better solution is to avoid temp table creation during run time. You can actually create a permanent table in your application database with some unique key to identify your session (to isolate cross session impacts, i.e 2 users using same functionality).
CREATE TABLE KV_TEMP_TABLE
(SESSION_ID VARCHAR2(100),
KV_CODE VARCHAR2(100)
);
--Adjust datatypes suitably
Then your query should look like
SELECT * FROM PERSONS T1, KV_TEMP_TABLE T2
WHERE T2.SESSION_ID = ?
AND T1.KV_CODE = T2.KV_CODE
--Bind your session id
Before issuing this query, you have to populate data into KV_TEMP_TABLE using normal insert statements (along with a session id).
Use this example to populates a temp table :
DECLARE #t TABLE
(
EmployeeID INT,
Certs VARCHAR(8000)
)
INSERT #t VALUES (1,'B.E.,MCA, MCDBA, PGDCA'), (2,'M.Com.,B.Sc.'), (3,'M.Sc.,M.Tech.')
SELECT EmployeeID,
LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS Certs
FROM
(
SELECT EmployeeID,CAST('<XMLRoot><RowData>' + REPLACE(Certs,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
FROM #t
)t
CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)
Once the temp table #t is populated, it can be used with JOINs to get the desired output.

Using update with an inner join SQL SERVER 2012

I needed som guidance as to how I can retrieve a column needed from a table with an INNER JOIN and in the same time update and insert a new column into my original table.
This is what I have written so far
SELECT DISTINCT
a.[CustNo],
X.CustomerID
FROM tblA_Add_CustomerID_Column a
INNER JOIN tblX x
ON x.CustomerCode = a.custno
My Table, tblA_Add_CustomerID_Column, only has a column named CustNo, and with the above query, I want to add CustomerID to Table, tblA_Add_CustomerID_Column.
How can I UPDATE and INSERT the column CustomerID from the table tblX?
My normal approach has always been doing the INNER JOIN , then take the results onto the excel sheet, and then import my excel file to the DB.
you can add the column with something like
alter table tblA_Add_CustomerID_Column add CustomerID int
then you can update the table using an update statement, something like
UPDATE tblA_Add_CustomerID_Column
SET CustomerID = x.cusomterID
FROM tblX x
WHERE custno = x.CustomerCode
You could do this instead:
ALTER TABLE tblA_Add_CustomerID_Column
ADD CustomerID INT;
EXEC('
UPDATE a
SET CustomerID = x.cusomterID
FROM tblA_Add_CustomerID_Column a
INNER JOIN tblX x ON x.CustomerCode = a.custno;
');

SQL Server - Multiple FROM keywords?

The search term is to ambiguous for google aparently. I am looking at a SQL call and it has 2 FROM keywords? I've never seen this before, can someone explain?
SELECT TOP(5) SUM(column) AS column, column
FROM ( SELECT DISTINCT column, column, column
FROM ((((((table table
INNER JOIN table table ON (column = column
AND column = 2
AND column != '' ))
INNER JOIN table table ON (column = column
AND (column = 144 OR column = 159 OR column = 162 OR column = 164 OR column = 163 OR column = 1 OR column = 2 OR column = 122 OR column = 155 OR column = 156 )))
inner join table table ON (column = column
AND column = 0 ))
INNER JOIN table ON (column = column ))
INNER JOIN table table ON ( column = column
AND (column = 102 OR column = 103 )))
INNER JOIN table table ON (column = column ))) TempTable
GROUP BY column ORDER BY column desc
You will note the multiple FROM keywords. It runs just fine. Just curious to what the purpose is.
This is called as subquery. You can use subquery within your main query
So subquery made the multiple FORM clause.
There's a reason why SQL is called a Structured Query Language: it lets you formulate queries that use other queries as their source, thus creating a hierarchical query structure.
This is a common practice: each FROM keyword is actually paired with its own SELECT, making the inner query a source for the outer one.
Proper formatting would help you understand what is going on: indenting inner SELECTs helps you see the structure of your query, making it easier to understand which part is used as the source of what other parts:
SELECT TOP(5) SUM(price) AS total_price, item_id
FROM ( -- The output of this query serves as input for the outer query
SELECT price, item
FROM order -- This may have its own selects, joins, etc.
GROUP BY order_id
)
GROUP BY item_id
SQL supports SELECTing from the results of another, nested SELECT. As already mentioned, the nested SELECT is called a subquery.
More details about subqueries and examples of their use in MSSQL Server can be found at http://technet.microsoft.com/en-us/library/ms189575(v=sql.105).aspx
Subquery used to select into an aliased column:
USE AdventureWorks2008R2;
GO
SELECT Ord.SalesOrderID, Ord.OrderDate,
(SELECT MAX(OrdDet.UnitPrice)
FROM AdventureWorks.Sales.SalesOrderDetail AS OrdDet
WHERE Ord.SalesOrderID = OrdDet.SalesOrderID) AS MaxUnitPrice
FROM AdventureWorks2008R2.Sales.SalesOrderHeader AS Ord
Using a subquery in the WHERE clause (from http://www.codeproject.com/Articles/200127/SQL-Joins-and-Subqueries)
-- Use a Subquery
SELECT * FROM AdventureWorks.Person.Address
WHERE StateProvinceID IN
(
SELECT StateProvinceID
FROM AdventureWorks.Person.StateProvince
WHERE StateProvinceCode = 'CA'
)
-- Use a Join
SELECT addr.*
FROM AdventureWorks.Person.Address addr
INNER JOIN AdventureWorks.Person.StateProvince state
ON addr.StateProvinceID = state.StateProvinceID
WHERE state.StateProvinceCode = 'CA'
You're seeing FROM clauses in subqueries. If you tabify the query it may be more obvious
SELECT TOP(5) SUM(column) AS column, column
FROM (
SELECT DISTINCT column, column, column
FROM ((((((table table
...
INNER JOIN table table ON (column = column ))) TempTable
GROUP BY column
ORDER BY column desc