How to UNION all two tables into a temp table? - sql

I've been trying to combine two tables into a temp table. My goal is to have the data of both tables available in one temp table
I tried a couple of things:
1.
SELECT * INTO #temp FROM Customers.Emails
UNION ALL
SELECT * INTO #temp FROM Customers.Location
SELECT *
INTO #temp
(Select
All column names here etc
FROM Customer.Emails
UNION
SELECT
All column names here etc
FROM Customer.Location)
When I tried 2 I got this error
Msg 263, Level 16, State 1, Line 1
Must specify table to select from.
Msg 1038, Level 15, State 5, Line 1
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.

Here are 3 methods to do the INSERT INTO #temp. Method 1 requires both tables to have the exact same column names and count. The other 2 methods require you to define the columns you want inserted since we aren't using SELECT * anymore.
CREATE TABLE emails (
email_address nvarchar(50)
);
CREATE TABLE locations (
email_address nvarchar(50)
);
INSERT INTO emails VALUES ('test#test.com');
INSERT INTO locations VALUES ('test2#test2.com');
--Method 1
SELECT * INTO #temp FROM emails
UNION ALL
SELECT * FROM locations
SELECT *
FROM #temp;
--Method 2
SELECT *
INTO #temp2
FROM (
SELECT
email_address
FROM emails
UNION ALL
SELECT
email_address
FROM locations
) as tbl
SELECT *
FROM #temp2;
--Method 3
WITH prelim AS (
SELECT
email_address
FROM emails
UNION ALL
SELECT
email_address
FROM locations
)
SELECT *
INTO #temp3
FROM prelim;
SELECT *
FROM #temp3;
Method 1 Results:
email_address
test#test.com
test2#test2.com
Method 2 Results:
email_address
test#test.com
test2#test2.com
Method 3 Results:
email_address
test#test.com
test2#test2.com
fiddle

Related

2 sql queries 2 different results using UNION

I have 2 queries that start with same tables but filter different columns. Both queries are unioned together so I can get a single count of people without duplication.
If I run the queries with the union commented out I have the same number of rows in each 1,953. When I run with the union I get 1,816 in one and 1,922 in the other.
My data is just an account # like 123456 in the first column and a 1/0 in the second column. Help me understand how this can happen if I am starting with the same number of rows.
Here is one of the queries
select distinct acct#,
case
when (lastFilledDate is not null and lastFilledDate<>'00/00/00') or
([Last Filled DC] is not null and [Last Filled DC]<>'00/00/00') or
(vivitrol is not null and vivitrol <>'00/00/00') or
(sublocade is not null and sublocade <>'00/00/00') or
(naltrexone is not null and naltrexone <>'00/00/00') then 1
else 0 end as result
from
(
select Acct#, DOB, [COE Contact Note], [COE-INTAKA Doc], [COE-MOM
Doc], lastFilledDate, [Last Filled DC],vivitrol,sublocade,naltrexone,
ROW_NUMBER() over (partition by Acct# order by [COE-INTAKA Doc] desc)
as apptRows
from tblAppBSCImportDashCOE2279 as main
where (([COE-MOM Doc]='Yes' and [COE Contact Note] is not null) or
[COE-MOM Doc]='No') and Appt is not null
) as sub
where apptRows=1
union
select distinct acctNo,
case
when
providerMAT='The Wright Center' and [COE-MOM Doc] is not null then
1
else 0
end as result
from
(
select acctNo, [COE-MOM Doc], MAT, providerMAT,
ROW_NUMBER() over (partition by acctNo order by COEBNMOM, [COE-MOM Doc]
desc) as apptRows
from tblAppBSCImportDashCOEHM2544 as main
where [COE-MOM Doc] is not null or COEBNMOM is not null
) as sub
where apptRows=1
results look like
acct# result
123456 1
234567 0
There is one possibility. The records you selected may result in duplicate records WITHIN each select statement. Let me try to illustrate with an example. (you can input the following query into your session to follow along)
IF OBJECT_ID('TEMPDB..#TEMP1') IS NOT NULL
DROP TABLE #TEMP1
IF OBJECT_ID('TEMPDB..#TEMP2') IS NOT NULL
DROP TABLE #TEMP2
CREATE TABLE #TEMP1(
id INT
,account INT
,amount INT
,yes_no INT
)
INSERT INTO #TEMP1 (id,account,amount,yes_no)
VALUES(1,123456,5,0)
,(2,123456,10,0)
,(3,123456,20,0)
CREATE TABLE #TEMP2(
id INT
,account INT
,amount INT
,yes_no INT
)
INSERT INTO #TEMP2 (id,account,amount,yes_no)
VALUES(4,123456,5,0)
,(5,123456,10,0)
,(6,123456,20,0)
SELECT *
FROM #TEMP1
SELECT *
FROM #TEMP2
Output of this is 2 tables with distinct records:
Now suppose I write queries that select account and the 'yes_no' column:
SELECT account,yes_no
FROM #TEMP1
SELECT account,yes_no
FROM #TEMP2
You can see that now all of the records are the same values within each select statement. So what do you think happens when I union these queries together?
SELECT account,yes_no
FROM #TEMP1
UNION
SELECT account,yes_no
FROM #TEMP2
UNION will output the distinct values of the ENTIRE OUTPUT, which also applies within each query. This is an extreme example of what I think you are experiencing. You need to include some sort of ID for each query such that it can be distinguished from other records within the query, like;
SELECT id,account,yes_no
FROM #TEMP1
UNION
SELECT id,account,yes_no
FROM #TEMP2

find the count from 2 tables

I want to find this count but when I execute the query it seems like it is stucked to "waiting for the query to complete" forever...any ideas?
SELECT (
SELECT COUNT(*)
FROM accidents,"Vechicles"
where "Date_of_accident"<'2010-01-01' and "Urban_or_Rural" like 'Urban' and "Age_Band_Of_Driver" like '26 - 35'
) AS count1
Because your query will select every row from the first table that matches your criteria, then for each row it will then select EVERY row from the second table that matches your criteria. This might end up being a huge number of rows that end up selected.
Here's an example:
CREATE TABLE #dumb (id INT);
CREATE TABLE #dumber (id INT);
INSERT INTO #dumb SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3;
INSERT INTO #dumber SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3;
SELECT * FROM #dumb, #dumber;
3 rows in each table, but the query selects 3 * 3 = 9 rows. Now imagine that there's 3 million rows in each table!

query with calculated fields

I've got table
Manga
idmanga title idauthor idgenre idmagazine
and table
Author
idauthor name surname
How to get table with fields
fullname title sumofids
name+surname idmanga+idauthor+idgenre+idmagazine
I can get fullname like this
select name+' '+surname as Fullname from Author
But how to get other fields in one query?
select CONVERT(VARCHAR,idmanga)
+CONVERT(VARCHAR,idauthor)
+CONVERT(VARCHAR,idgenre)
+CONVERT(VARCHAR,idmagazine)
That should do it all in one string.
Add + ' ' + to put in spaces.
To add all the values together, your query should work to get the values for every row. If you want to group by the Name to roll the results up, use the SUM() and you'll get one row per unique name combination
create table Test ( Name varchar(10)
,idmanga int
,idauthor int
,idgenre int
,idmagazine int)
insert into Test
select 'Roger',1,2,3,4
union select 'Bob',4,5,6,7
union select 'Roger',8,9,10,11
union select 'Bob',12,13,14,15
union select 'Bill',16,17,18,19
select Name
, idmanga+idauthor+idgenre+idmagazine
from Test
select Name
, SUM(idmanga+idauthor+idgenre+idmagazine)
from Test
group by Name

Make SQL Select same row multiple times

I need to test my mail server. How can I make a Select statement
that selects say ID=5469 a thousand times.
If I get your meaning then a very simple way is to cross join on a derived query on a table with more than 1000 rows in it and put a top 1000 on that. This would duplicate your results 1000 times.
EDIT: As an example (This is MSSQL, I don't know if Access is much different)
SELECT
MyTable.*
FROM
MyTable
CROSS JOIN
(
SELECT TOP 1000
*
FROM
sysobjects
) [BigTable]
WHERE
MyTable.ID = 1234
You can use the UNION ALL statement.
Try something like:
SELECT * FROM tablename WHERE ID = 5469
UNION ALL
SELECT * FROM tablename WHERE ID = 5469
You'd have to repeat the SELECT statement a bunch of times but you could write a bit of VB code in Access to create a dynamic SQL statement and then execute it. Not pretty but it should work.
Create a helper table for this purpose:
JUST_NUMBER(NUM INT primary key)
Insert (with the help of some (VB) script) numbers from 1 to N. Then execute this unjoined query:
SELECT MYTABLE.*
FROM MYTABLE,
JUST_NUMBER
WHERE MYTABLE.ID = 5469
AND JUST_NUMBER.NUM <= 1000
Here's a way of using a recursive common table expression to generate some empty rows, then to cross join them back onto your desired row:
declare #myData table (val int) ;
insert #myData values (666),(888),(777) --some dummy data
;with cte as
(
select 100 as a
union all
select a-1 from cte where a>0
--generate 100 rows, the max recursion depth
)
,someRows as
(
select top 1000 0 a from cte,cte x1,cte x2
--xjoin the hundred rows a few times
--to generate 1030301 rows, then select top n rows
)
select m.* from #myData m,someRows where m.val=666
substitute #myData for your real table, and alter the final predicate to suit.
easy way...
This exists only one row into the DB
sku = 52 , description = Skullcandy Inkd Green ,price = 50,00
Try to relate another table in which has no constraint key to the main table
Original Query
SELECT Prod_SKU , Prod_Descr , Prod_Price FROM dbo.TB_Prod WHERE Prod_SKU = N'52'
The Functional Query ...adding a not related table called 'dbo.TB_Labels'
SELECT TOP ('times') Prod_SKU , Prod_Descr , Prod_Price FROM dbo.TB_Prod,dbo.TB_Labels WHERE Prod_SKU = N'52'
In postgres there is a nice function called generate_series. So in postgreSQL it is as simple as:
select information from test_table, generate_series(1, 1000) where id = 5469
In this way, the query is executed 1000 times.
Example for postgreSQL:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; --To be able to use function uuid_generate_v4()
--Create a test table
create table test_table (
id serial not null,
uid UUID NOT NULL,
CONSTRAINT uid_pk PRIMARY KEY(id));
-- Insert 10000 rows
insert into test_table (uid)
select uuid_generate_v4() from generate_series(1, 10000);
-- Read the data from id=5469 one thousand times
select id, uid, uuid_generate_v4() from test_table, generate_series(1, 1000) where id = 5469;
As you can see in the result below, the data from uid is read 1000 times as confirmed by the generation of a new uuid at every new row.
id |uid |uuid_generate_v4
----------------------------------------------------------------------------------------
5469|"10791df5-ab72-43b6-b0a5-6b128518e5ee"|"5630cd0d-ee47-4d92-9ee3-b373ec04756f"
5469|"10791df5-ab72-43b6-b0a5-6b128518e5ee"|"ed44b9cb-c57f-4a5b-ac9a-55bd57459c02"
5469|"10791df5-ab72-43b6-b0a5-6b128518e5ee"|"3428b3e3-3bb2-4e41-b2ca-baa3243024d9"
5469|"10791df5-ab72-43b6-b0a5-6b128518e5ee"|"7c8faf33-b30c-4bfa-96c8-1313a4f6ce7c"
5469|"10791df5-ab72-43b6-b0a5-6b128518e5ee"|"b589fd8a-fec2-4971-95e1-283a31443d73"
5469|"10791df5-ab72-43b6-b0a5-6b128518e5ee"|"8b9ab121-caa4-4015-83f5-0c2911a58640"
5469|"10791df5-ab72-43b6-b0a5-6b128518e5ee"|"7ef63128-b17c-4188-8056-c99035e16c11"
5469|"10791df5-ab72-43b6-b0a5-6b128518e5ee"|"5bdc7425-e14c-4c85-a25e-d99b27ae8b9f"
5469|"10791df5-ab72-43b6-b0a5-6b128518e5ee"|"9bbd260b-8b83-4fa5-9104-6fc3495f68f3"
5469|"10791df5-ab72-43b6-b0a5-6b128518e5ee"|"c1f759e1-c673-41ef-b009-51fed587353c"
5469|"10791df5-ab72-43b6-b0a5-6b128518e5ee"|"4a70bf2b-ddf5-4c42-9789-5e48e2aec441"
Of course other DBs won't necessarily have the same function but it could be done:
See here.
If your are doing this in sql Server
declare #cnt int
set #cnt = 0
while #cnt < 1000
begin
select '12345'
set #cnt = #cnt + 1
end
select '12345' can be any expression
Repeat rows based on column value of TestTable. First run the Create table and insert statement, then run the following query for the desired result.
This may be another solution:
CREATE TABLE TestTable
(
ID INT IDENTITY(1,1),
Col1 varchar(10),
Repeats INT
)
INSERT INTO TESTTABLE
VALUES ('A',2), ('B',4),('C',1),('D',0)
WITH x AS
(
SELECT TOP (SELECT MAX(Repeats)+1 FROM TestTable) rn = ROW_NUMBER()
OVER (ORDER BY [object_id])
FROM sys.all_columns
ORDER BY [object_id]
)
SELECT * FROM x
CROSS JOIN TestTable AS d
WHERE x.rn <= d.Repeats
ORDER BY Col1;
This trick helped me in my requirement.
here, PRODUCTDETAILS is my Datatable
and orderid is my column.
declare #Req_Rows int = 12
;WITH cte AS
(
SELECT 1 AS Number
UNION ALL
SELECT Number + 1 FROM cte WHERE Number < #Req_Rows
)
SELECT PRODUCTDETAILS.*
FROM cte, PRODUCTDETAILS
WHERE PRODUCTDETAILS.orderid = 3
create table #tmp1 (id int, fld varchar(max))
insert into #tmp1 (id, fld)
values (1,'hello!'),(2,'world'),(3,'nice day!')
select * from #tmp1
go
select * from #tmp1 where id=3
go 1000
drop table #tmp1
in sql server try:
print 'wow'
go 5
output:
Beginning execution loop
wow
wow
wow
wow
wow
Batch execution completed 5 times.
The easy way is to create a table with 1000 rows. Let's call it BigTable. Then you would query for the data you want and join it with the big table, like this:
SELECT MyTable.*
FROM MyTable, BigTable
WHERE MyTable.ID = 5469

Best practice regarding searching keywords with sql

I have three tables
[USER] --Master user table
[KEYWORD] --Master keyword table
[USER_KEYWORD] --[USER]-[KEYWORD] mapping table
Below is the structure in my db
GO
--master user table
CREATE TABLE [USER]
(
[USERID] INT IDENTITY,
[NAME] VARCHAR(50)
)
GO
--master keyword table
CREATE TABLE [KEYWORD]
(
[KEYWORDID] INT IDENTITY,
[KEYWORD] VARCHAR(50)
)
GO
--x table user_keyword
CREATE TABLE [USER_KEYWORD]
(
[USERID] INT ,
[KEYWORDID] INT
)
GO
--Insert data in master user table
INSERT INTO [USER]
SELECT 'TESTUSER1'
UNION ALL
SELECT 'TESTUSER2'
UNION ALL
SELECT 'TESTUSER3'
UNION ALL
SELECT 'TESTUSER4'
GO
--Insert data in master keyword table
INSERT INTO [KEYWORD]
SELECT 'ASP'
UNION ALL
SELECT 'ASP.NET 3.5'
UNION ALL
SELECT 'C#'
UNION ALL
SELECT 'JAVA'
UNION ALL
SELECT 'ASP.NET'
UNION ALL
SELECT 'SQL'
UNION ALL
SELECT 'SQL SERVER'
UNION ALL
SELECT 'SQL SERVER 2005'
UNION ALL
SELECT 'SQL SERVER 2008'
GO
--Insert data in user keyword table
INSERT INTO [USER_KEYWORD]
SELECT 1,1
UNION ALL
SELECT 2,2
UNION ALL
SELECT 3,3
UNION ALL
SELECT 4,4
UNION ALL
SELECT 1,2
UNION ALL
SELECT 2,3
UNION ALL
SELECT 3,4
UNION ALL
SELECT 4,1
UNION ALL
SELECT 2,3
UNION ALL
SELECT 3,4
UNION ALL
SELECT 4,6
UNION ALL
SELECT 3,6
UNION ALL
SELECT 4,6
UNION ALL
SELECT 2,7
UNION ALL
SELECT 3,8
UNION ALL
SELECT 4,9
GO
CREATE PROC TEST_SEARCH_KEYWORDS
#SEARCHKEYWORD VARCHAR(50)
AS
BEGIN
SELECT K.[KEYWORD],COUNT(UK.[KEYWORDID]) AS [KEWWORDCOUNT] FROM [KEYWORD] K
INNER JOIN [USER_KEYWORD] UK
ON K.[KEYWORDID]=UK.[KEYWORDID]
WHERE K.[KEYWORD] LIKE (#SEARCHKEYWORD+ '%')
GROUP BY K.[KEYWORD]
END
--TEST EXAMPLES
EXEC TEST_SEARCH_KEYWORDS 'ASP'
--0UTPUT
KEYWORD KEWWORDCOUNT
-------------------------------------------------- ------------
ASP 2
ASP.NET 3.5 2
--TEST EXAMPLES
EXEC TEST_SEARCH_KEYWORDS 'SQL'
--0UTPUT
KEYWORD KEWWORDCOUNT
-------------------------------------------------- ------------
SQL 3
SQL SERVER 1
SQL SERVER 2005 1
SQL SERVER 2008 1
I have one sp named TEST_SEARCH_KEYWORDS to search records based on keywords that is provided from outside.Currently i am using like condition in sp. I want to know that is this will be good to search records from database using like as in future my records will keep on increasing .I don't want to use full text search
as i have to cope with sql server 2000 also.
if you keep searching like:
WHERE K.[KEYWORD] LIKE (#SEARCHKEYWORD+ '%')
then your query will use an index, and should still perform well as the table grows. However, if you change it to:
WHERE K.[KEYWORD] LIKE ('%'+ #SEARCHKEYWORD+ '%')
then it will not, and it will table scan, which will cause bad performance as your table grows.
One (storage-hungry) solution would be to pre-compute and store a number keyword prefices alongside the actual keyword itself. Then based on the look criteria you would do a direct equality comparison on the relevant prefix column (if one existed) or else fall back to performing a "like" comparison.
For example, suppose to impose a limit that the search word must contain at least 3 characters. You could create columns Prefix3Chars, Prefix4Chars, Prefix5Chars. Say the user enters the search word "Hello" and your database contained a key word "Hello, World". You would elect to search on the Prefix5Chars column and would match against the key word "Hello, World". If the user performed a search with key word "Hello, W" you would fall back to searching using "like".