SQL - Insert Stored Procedure Results into Temp Table - sql

I have a fully working stored procedure grabbing data from different tables using joins. I am currently using the below SELECT statement to select the data I require:
SELECT
ClientReference, ReferenceNumber, Text3,
ReceiptDate, [dbo].[Complaint].[Description],
ActionTaken, dbo.Category.Name, dbo.CategoryOption.FullName,
dbo.Complaint.AuditCreatedBy,
dbo.UserGroup.Name, dbo.Complaint.LoggedByUserId,
dbo.Complaint.LoggedByTime
FROM
dbo.Complaint
Now what I want to be able to do is insert this data into a temporary table. However, INSERT INTO does not work as I have two columns (resulting from my join) called Name.
How would I go about solving this?

Just alias one of the Name columns:
SELECT
ClientReference,
ReferenceNumber,
Text3,
ReceiptDate,
Complaint.Description,
ActionTaken,
Category.Name As CategoryName,
CategoryOption.FullName,
Complaint.AuditCreatedBy,
UserGroup.Name,
Complaint.LoggedByUserId,
Complaint.LoggedByTime
INTO #tempTable
FROM
dbo.Complaint
...

Related

Insert data into multiple tables from one select statement in sql

I need to insert data into two different tables via a select statement.This select statement is calling an inline TVF.
What I have so far is :
INSERT INTO #Temp2 (RowNumber, ValFromUser, ColumnName, ValFromFunc, FuncWeight, percentage)
SELECT
RowNumber, #hospitalname, 'hospitalname',
PercentMatch, #constVal, PercentMatch * #constVal
FROM
dbo.Matchhospitalname (#hospitalname)
But there are certain columns that need to be supplied to a permanent table dbo.Cache.
Above mentioned query is called multiple times in the procedure.
Insert into dbo.Cache(StringSearched, ColName, RowId, PercentMatch)
select
ValFromUser, ColumnName, RowNumber, Max(ValFromFunc) as Percentage
from
#Temp2
group by
ValFromUser, ColumnName, RowNumber
Adding data into dbo.Cache separately as above would make all the previously added values to be added as many times as this statement is executed which is of course not desirable.
May be if it is not possible at all to add data to two tables via one select, we can do something like adding only those rows that were added in last insert statement only ?
Can I get some directions on this, please?
Edit : As suggested, I tried using OUTPUT INTO this way but Group by seems to be at the wrong place.The grouped rowsare to be inserted only in dbo.Cache and not in #Temp2
How do I solve this ?
INSERT INTO #Temp2 (RowNumber,ValFromUser,ColumnName,ValFromFunc,FuncWeight,percentage)OUTPUT
INSERTED.ValFromUser,
INSERTED.ColumnName,
INSERTED.RowNumber,
MAX(INSERTED.ValFromFunc)
INTO dbo.CACHE
(StringSearched, ColName, RowId, PercentMatch)
Group By Inserted.ValFromUser, Inserted.ColumnName, Inserted.RowNumber
SELECT RowNumber,#firstname,'firstname',PercentMatch,#constVal,PercentMatch * #constVal FROM dbo.MatchFirstName(#firstname)
You can do it via an output clause or more typically you can put a trigger on a table. In other words you can create an after insert trigger on temp table '#temp2'. I have never seen a trigger on a temp table but its possible. You will have to recreate the trigger every time the temp table is recreated. Remember that #temp2 will only exist (and be visible) in the session that it is created in.

Openquery statement in SQL Server

I am fairly new to SQL, and I am hoping someone can help me with a problem I'm having. I haven't been able to find any answers helping me figure out this exact problem.
I have two tables in two SQL Server databases on two different servers that I want to compare using the column ItemID. I want to find records from Table1 that have an ItemID that does not exist in Table2 and insert those into a table variable. I have the following code:
--Create table variable to hold query results
DECLARE #ItemIDTable TABLE
(
[itemid][NVARCHAR](20) NULL
);
--Query data and insert results into table variable
INSERT INTO #ItemIDTable
([itemid])
SELECT a.[itemid]
FROM database1.dbo.table1 a
WHERE NOT EXISTS (SELECT 1
FROM [Database2].[dbo].[table2]
WHERE a.itemid = [Database2].[dbo].[table2].[itemid])
ORDER BY itemid
This works on a test server where the two databases are on the same server, but not in real life where they are on different servers. I tried the following using OPENQUERY, but I know I haven't got it quite right.
--Create table variable to hold query results
DECLARE #ItemIDTable TABLE
(
[ItemID][nvarchar](20) NULL
);
--Query data and insert results into table variable
INSERT INTO #ItemIDTable
([ItemID])
SELECT a.[ItemID]
FROM Database1.dbo.Table1 a
WHERE NOT EXISTS (SELECT 1
FROM OPENQUERY([Server2], SELECT * FROM [Database2].[dbo].[Table2]')
WHERE a.ItemID = [Database2].[dbo].[Table2].[ItemID])
ORDER BY ItemID
I'm pretty sure I need to do something in the WHERE clause, where I have the two databases on two servers, I'm just not quite sure how to structure it. Could anyone help?
You can't create an OPENQUERY that is correlated to an outer query. You could populate a temp table with the results of an OPENQUERY and do your WHERE NOT EXISTS against the temp table, or you might want to look into Synonyms.
Openquery works like this:
select *
from openquery
(LINKED_SERVER_NAME,
'select query goes here'
)
Note that the sql portion is single quoted. That means you might have to quote the quotes if necessary. For example:
select *
from openquery
(LINKED_SERVER_NAME,
'
select SomeTextField
from SomeTable
where SomeDateField = ''20141014''
'
)

Insert query results into table in ms access 2010

I need to transform data from one schema into another in an MS Access database. This involves writing queries to select data from the old schema and then inserting the results of the queries into tables in the new schema. The below is an example of what I am trying to do. The SELECT component of the below works fine, but the INSERT component does not work. Can someone show me how to fix the below so that it effectively inserts the results of the SELECT statement into the destination table?
INSERT INTO CompaniesTable
(CompanyName)
VALUES
(
SELECT DISTINCT
IIF(a.FIRM_NAME IS NULL, b.SUBACCOUNT_COMPANY_NAME, a.FIRM_NAME) AS CompanyName
FROM
(SELECT ContactID, FIRM_NAME, SUBACCOUNT_COMPANY_NAME FROM qrySummaryData) AS a
LEFT JOIN
(SELECT ContactID, FIRM_NAME, SUBACCOUNT_COMPANY_NAME FROM qrySummaryData) AS b
ON a.ContactID = b.ContactID
);
The definition of the target table (CompaniesTable) is:
CompanyID Autonumber
CompanyName Text
Description Text
WebSite Text
Email Text
TypeNumber Number
Maybe you have a typo but joining a table to itself you don't need the join, this should work fine. With an insert on a select statement you don't use the values keyword.
INSERT INTO CompaniesTable (CompanyName,Description,Website,Email,TypeNumber)
SELECT DISTINCT IIF(FIRM_NAME IS NULL, SUBACCOUNT_COMPANY_NAME, FIRM_NAME),
'','','',0
FROM qrySummaryData

SQL Insert/Update Issue

I am trying to update one table from another, im able to update fine as long as the customer record exists, but there are some entries that dont.
To solve this i've tried running the following insert
SELECT *
INTO SalBudgetCust
FROM SalBudgetCust_temp
WHERE NOT EXISTS (
SELECT Customer
FROM SalBudgetCust
WHERE Customer = SalBudgetCust_temp.Customer
)
but im prompted with
There is already an object named 'SalBudgetCust' in the database.
Im stuck at this point... could anyone offer a little guideance?
SELECT INTO implicitly creates the table you name. You should instead use INSERT INTO ... SELECT * FROM ..., so that the existing table is used.
It should be INSERT INTO instead of SELECT * INTO ... like
INSERT INTO SalBudgetCust SELECT * FROM SalBudgetCust_temp
WHERE NOT EXISTS
(
SELECT Customer FROM SalBudgetCust WHERE Customer = SalBudgetCust_temp.Customer
)
The general syntax to insert data of one table into another is :
INSERT INTO new_table
SELECT * FROM old_table
WHERE some_condition;
Where, new_table is the table where you want to insert data, old_table is table from where you are fetching data and some_condition is the expression / condition based upon which you want to fetch data from old table.
You may use other clauses like order by, group by, and even sub queries after where clause.
May refer this SQL INSERT INTO and it's subsequent pages.

How to combine IN operator with LIKE condition (or best way to get comparable results)

I need to select rows where a field begins with one of several different prefixes:
select * from table
where field like 'ab%'
or field like 'cd%'
or field like "ef%"
or...
What is the best way to do this using SQL in Oracle or SQL Server? I'm looking for something like the following statements (which are incorrect):
select * from table where field like in ('ab%', 'cd%', 'ef%', ...)
or
select * from table where field like in (select foo from bar)
EDIT:
I would like to see how this is done with either giving all the prefixes in one SELECT statement, of having all the prefixes stored in a helper table.
Length of the prefixes is not fixed.
Joining your prefix table with your actual table would work in both SQL Server & Oracle.
DECLARE #Table TABLE (field VARCHAR(32))
DECLARE #Prefixes TABLE (prefix VARCHAR(32))
INSERT INTO #Table VALUES ('ABC')
INSERT INTO #Table VALUES ('DEF')
INSERT INTO #Table VALUES ('ABDEF')
INSERT INTO #Table VALUES ('DEFAB')
INSERT INTO #Table VALUES ('EFABD')
INSERT INTO #Prefixes VALUES ('AB%')
INSERT INTO #Prefixes VALUES ('DE%')
SELECT t.*
FROM #Table t
INNER JOIN #Prefixes pf ON t.field LIKE pf.prefix
you can try regular expression
SELECT * from table where REGEXP_LIKE ( field, '^(ab|cd|ef)' );
If your prefix is always two characters, could you not just use the SUBSTRING() function to get the first two characters of "field", and then see if it's in the list of prefixes?
select * from table
where SUBSTRING(field, 1, 2) IN (prefix1, prefix2, prefix3...)
That would be "best" in terms of simplicity, if not performance. Performance-wise, you could create an indexed virtual column that generates your prefix from "field", and then use the virtual column in your predicate.
Depending on the size of the dataset, the REGEXP solution may or may not be the right answer. If you're trying to get a small slice of a big dataset,
select * from table
where field like 'ab%'
or field like 'cd%'
or field like "ef%"
or...
may be rewritten behind the scenes as
select * from table
where field like 'ab%'
union all
select * from table
where field like 'cd%'
union all
select * from table
where field like 'ef%'
Doing three index scans instead of a full scan.
If you know you're only going after the first two characters, creating a function-based index could be a good solution as well. If you really really need to optimize this, use a global temporary table to store the values of interest, and perform a semi-join between them:
select * from data_table
where transform(field) in (select pre_transformed_field
from my_where_clause_table);
You can also try like this, here tmp is temporary table that is populated by the required prefixes. Its a simple way, and does the job.
select * from emp join
(select 'ab%' as Prefix
union
select 'cd%' as Prefix
union
select 'ef%' as Prefix) tmp
on emp.Name like tmp.Prefix