Select Inside a select statement - sql

I am trying to create a table in Database A from a table in database B. I have an idea with the query. In the database A, the table needs MerchantID and can get it from database B by using the query (Select MerchantID from Merchant_Location where LocationID= 'particular LocationID').
I need some help with the syntax for a query like this in SQL Server 2005. Thank you in advance!
INSERT INTO A.dbo.Merchant_Category (MerchantCategoryID, MerchantID)
SELECT MerchantLocationCategoryID, (MerchantID from Merchant_Location where LocationID = #Location) as MerchantID FROM B.dbo.Merchant_Location_Category

You want to use a SELECT INTO statement. What this does is execute a query and then inserts the results into your designated table.
SELECT field1, field2, field3 FROM db_b.TABLE_IN_DB_B
INTO db_a.TABLE_IN_DB_A;
Read more about the SELECT INTO statement Here

You can JOIN across databases in an INSERT, just like a SELECT. Most systems will allow it in an UPDATE as well.
INSERT INTO A.dbo.Merchant_Category (
MerchantCategoryID, MerchantID
)
SELECT LC.MerchantLocationCategoryID, L.MerchantId
FROM B.dbo.Merchant_Location_Category as LC
JOIN A.dbo.Merchant_Location as L ON
LC.LocationID = L.LocationID

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 to fetch distinct records from SQL Server Compact database

How do I get unique records from multiple tables using SQL Server Compact?
I tried with this SQL statement:
SELECT Tbl_Customer.Name, Tbl_Room.Room_Number
FROM Tbl_Customer
INNER JOIN Tbl_Room ON Tbl_Customer.Customer_number = Tbl_Room.Customer_Number
WHERE Tbl_Customer.Customer_number IN (SELECT DISTINCT Tbl_Customer.Customer_number
FROM Tbl_Customer)
I don't understand why there is this WHERE statement. You are trying to get records from Tbl_Customer that have Customer_number existing in the same table - Tbl_Customer. Without this condition, you can use
SELECT c.Name, r.Room_Number
FROM Tbl_Customer c
INNER JOIN Tbl_Room r ON c.Customer_number = r.Customer_Number
GROUP BY c.Name, r.Room_Number
I hope it helps.
EDIT: In this case SELECT DISTINCT should give the same results and even generate exactly the same query execution plan.

SQL subqueries or inner join?

I am building a new web application and have had a basic understanding of sql queries but I am stuck in this particular query.
These are the two tables I will be using this query. The "followingID" in the first table points to the "id" of the second table.
dbo.T_FOLLOWING_GROUP
-id
-groupLookupID
-followingID
-order
dbo.FOLLOWING
-id
-userID
-followingID
I need to get all the rows in dbo.FOLLOWING based on known values that I have of "userID" and "groupLookupID".
Is this enough information to go off of? I know there are ways of doing
`SELECT * FROM dbo.FOLLOWING
WHERE (insert select subquery here)`
Or is there some sort of inner join I need to use?
INNER JOIN
SELECT AnyTableName.AnyColumnName1, AnyTableName.AnyColumnName2, ..... --- out these two tables
FROM dbo.T_FOLLOWING_GROUP INNER JOIN dbo.FOLLOWING
ON dbo.T_FOLLOWING_GROUP.followingID = dbo.FOLLOWING.id
And then you can add WHERE Clause in the end to futher filter the result set
IN Query
SELECT Column1, Column2, Column3, ...........
FROM dbo.T_FOLLOWING_GROUP
WHERE followingID IN (
SELECT DISTINCT id FROM dbo.FOLLOWING
)
To have all in one query (using joins) try this:
SELECT f.*
FROM dbo.FOLLOWING f
LEFT JOIN dbo.T_FOLLOWING_GROUP fg on (f.id=fg.followingID)
WHERE f.userID=xxx AND fg.groupLookupID=yyy
(use your known values in place of xxx and yyy).

Update using Distinct SUM

I have found a few good resources that show I should be able to merge a select query with an update, but I just can't get my head around of the correct formatting.
I have a select statement that is getting info for me, and I want to pretty much use those results to Update an account table that matches the accountID in the select query.
Here is the select statement:
SELECT DISTINCT SUM(b.workers)*tt.mealTax as MealCost,b.townID,b.accountID
FROM buildings AS b
INNER JOIN town_tax AS tt ON tt.townID = b.townID
GROUP BY b.townID,b.accountID
So in short I want the above query to be merged with:
UPDATE accounts AS a
SET a.wealth = a.wealth - MealCost
Where MealCost is the result from the select query. I am sure there is a way to put this into one, I just haven't quite been able to connect the dots to get it to run consistently without separating into two queries.
First, you don't need the distinct when you have a group by.
Second, how do you intend to link the two results? The SELECT query is returning multiple rows per account (one for each town). Presumably, the accounts table has only one row. Let's say that you wanted the average MealCost for the update.
The select query to get this is:
SELECT accountID, avg(MealCost) as avg_Mealcost
FROM (SELECT SUM(b.workers)*tt.mealTax as MealCost, b.townID, b.accountID
FROM buildings AS b INNER JOIN
town_tax AS tt
ON tt.townID = b.townID
GROUP BY b.townID,b.accountID
) a
GROUP BY accountID
Now, to put this into an update, you can use syntax like the following:
UPDATE accounts
set accounts.wealth = accounts.wealth + asum.avg_mealcost
from (SELECT accountID, avg(MealCost) as avg_Mealcost
FROM (SELECT SUM(b.workers)*tt.mealTax as MealCost, b.townID, b.accountID
FROM buildings AS b INNER JOIN
town_tax AS tt
ON tt.townID = b.townID
GROUP BY b.townID,b.accountID
) a
GROUP BY accountID
) asum
where accounts.accountid = asum.accountid
This uses SQL Server syntax, which I believe is the same as for Oracle and most other databases. Mysql puts the "from" clause before the "set" and allows an alias on "update accounts".

use a sql select statement to get parameters for 2nd select statement

I am trying to write a sql statement that
I have 2 tables Store & StoreTransactions.
My first select command looks like
SELECT [StoreID],[ParentStoreID]
FROM Store
Very simple stuff. How do I take the returned StoreID's and use them for my 2nd select statement?
SELECT [StoreTransactionID],[TransactionDate],[StoreID]
FROM StoreTransactions
WHERE StoreID = returned values from the above query
Any help would be great!
SELECT [StoreTransactionID],[TransactionDate],[StoreID]
FROM StoreTransactions
WHERE StoreID in (select StoreId from Store)
This is known as a nested select, or inner select.
Couple of other ways of doing it...
SELECT [StoreTransactionID],[TransactionDate],[StoreID]
FROM StoreTransactions st
WHERE EXISTS
(
SELECT *
FROM Store s
WHERE s.[StoreID] = st.[StoreID]
)
And
SELECT [StoreTransactionID],[TransactionDate],st.[StoreID]
FROM StoreTransactions st
INNER JOIN Store s ON s.[StoreID] = st.[StoreID]
An alternative way of writing it is to use an INNER JOIN
SELECT [StoreTransactionID],[TransactionDate],[StoreTransactions.StoreID]
FROM StoreTransactions INNER JOIN Store ON StoreTransactions.StoreID=Store.StoreID
This may be more efficient in some RDBMSs.
If your Store query also includes a WHERE clause, you can just add that to the query above.