Creating SQL Connection in Excel that creates and drops temporary tables - sql

I've created query that runs perfectly in Microsoft SQL Server and it utilizes temporary tables it creates and drops. I now want to create a data connection in Microsoft Excel that will run my query and display the results in Excel, so that business partners who do not know SQL can utilize the report.
However, when I try to run the query in a data connection in excel I get errors like the following:
"Database name 'database' ignored, referencing object in tempdb."
OR
"The query did not run, or the database table could not be opened. Check the database server or contact your database administrator. Make sure the external database is available and hasn't been moved or reorganized, then try the operation again."
I then tried to use the phrase "SET NOCOUNT on" before creating my temporary tables but it did not resolve the issue and I still have no report.
Here is how my code is set up
select
x.PRODUCT_ID,
y.SETID,
LW = ISNULL (SUM(y.SALES_QTY) ,0)
INTO database.#tmpLastWeek
--#tempLastWeek is a temporary table I am creating here and inserting values into
from
database.sales_table y
inner join
database.product_table x
on y.PRODUCT_ID = x.PRODUCT_ID
and x.SETID = y.SETID
where
y.stores IN (
'storeslist'
)
and y.sales_week = #this_week - 1
and y.sales_year = #this_year
group by
x.PRODUCT_ID,
y.SETID,
x.DESCR
Then I select from the temporary table #tmpLastWeek
select * from #tmpLastWeek
Then finally I drop this temporary table so that it can be ran again
drop table #tmpLastWeek
Any advice or suggestions on getting this query to be ran thru and SQL connection in Excel would be much appreciated! Thanks!!!!

Related

Write to database from R using RODBC:sqlSave not working

I have a SQL database table that I want to populate with data from my R data.frame. The SQL target table ("SQL_table") already exists in the ODBC SQL database, but is empty of data. When I try to write my data, it always errors out. It looks like it's always trying to create the SQL data table?
Here is my code:
con <- odbcConnect("SQL_Database", uid="my_user_name", pwd="my_password")
RODBC::sqlSave(channel=con , dat=my_df, tablename = "SQL_table", append=T)
Here is the error received:
Error in RODBC::sqlSave(channel = con, dat = my_df, :
42S01 2714 [Microsoft][ODBC SQL Server Driver][SQL Server]There is already an object named 'SQL_table' in the database.
[RODBC] ERROR: Could not SQLExecDirect 'CREATE TABLE SQL_table ("rownames" varchar(255) ..."
Troubleshooting thus far:
I tried running it with append=T & append=F. Both ways it tries to create the table, making no difference.
I confirmed that my data schema exactly matches the schema of the target SQL table.
I confirmed that I can write to the SQL database.
I tried dropping the database table, and then have R create it from scratch. Doing so my data will populate then create the table in the SQL database, but not populate it. In other words, it sends the column names and data types, but not the actual data.
Thank you in advance!

How to create a table from a linked server into the local machine

I need to copy tables from a linked server onto my local machine. I am working in SQL management studio. The linked server is Oracle based. My end goal is to set up a stored proc that deletes a table if it exists and creates a new table in its place with refreshed data. This will be done for many tables as needed. The issue with the below code is that I get the error:
Incorrect syntax near the keyword 'SELECT'.
I am stuck at creating the table.
CREATE TABLE test AS
SELECT DUMMY
FROM OPENQUERY (LServer, '
Select *
from sourceT
');
The data in the dummy table is just one column with a single value "x". I have seen posts that suggest using a certain notation in naming the linked server table, like <server.database.schema.tablename> but this doesn't seem to work,even if I just run the select statement using the openquery. If I just run the select part in the script above, this does work.
CREATE TABLE test AS
Is valid in Oracle but not SQL Server
You want
-- if the table already exists drop it
DROP TABLE IF EXISTS test;
-- now create a table and load into it
SELECT DUMMY
INTO test
FROM OPENQUERY (LServer, '
Select *
from sourceT')

I cannot query or check for existing tables in tempdb

I have a strange problem where I cannot query the tempdb to check what tables exists using the following code:
select * from tempdb.sys.tables
where name = OBJECT_NAME(OBJECT_ID('##NewTableX'))
Even just selecting everything from tempdb.sys.tables doesn't work using:
select * from tempdb.sys.tables
I also cannot check for an existing table in the tempdb using the following code:
if OBJECT_ID('tempdb..##NewTableX') IS NOT NULL
begin
DROP TABLE ##NewTableX
end
Every time I try to execute any code to do with the tempdb the query runs for ever in SQL Server Management Studio.
If I create a brand new temporary table using insert into code that works
select * into ##NewTableY from OPENQUERY(QBREMOTE,''sp_report ProfitAndLossByJob show Amount_Title, Text, Label, Amount parameters DateFrom = {d''''''2021-01-01''''''}, DateTo = {d''''''2021-12-30''''''}, EntityFilterFullNameWithChildren="'+REPLACE('ALL','''','''''')+'", SummarizeColumnsBy = "TotalOnly"'')'
Can anyone shed any light on what might be happening with the tempdb and why I cannot query it?
I tried to find what was blocking it but nothing worked. In the end I had to restart the Sql server, which I was trying to avoid doing. This solved my problem

Create Table by Copying Structure of Existing Table

I am trying to create a new table by copying an existing table in SQL Server 2008 using Management Studio. The existing table contains no data. I am using the following code but am receiving an error for Incorrect Syntax near AS. I am not sure what is wrong here. I am a SQL newb and any help would be appreciated. Thanks.
CREATE TABLE Drop_Centers_Detail
AS (Select * From Centers_Detail)
like this, however this will not create indexes and constraints
select * into Drop_Centers_Detail
from Centers_Detail
where 1 = 0
In Sql Server Managment Studio, right-click your existing table and select Script Table as > Create to > New Query Editor Window. This will give you a better starting script that you can use as the base for your new schema.
1) I would suggest generating a create script from the table you want to copy, and then run that on your destination database.
2) Write a Insert statement in another SQL Query window to import that data
Insert Into Database1.Table1(Field1, Field2)
Select Field1, Field2 From Database2.Table

Select Query on 2 tables, on different database servers

I am trying to generate a report by querying 2 databases (Sybase) in classic ASP.
I have created 2 connection strings:
connA for databaseA
connB for databaseB
Both databases are present on the same server (don't know if this matters)
Queries:
q1 = SELECT column1 INTO #temp FROM databaseA..table1 WHERE xyz="A"
q2 = SELECT columnA,columnB,...,columnZ FROM table2 a #temp b WHERE b.column1=a.columnB
followed by:
response.Write(rstsql) <br>
set rstSQL = CreateObject("ADODB.Recordset")<br>
rstSQL.Open q1, connA<br>
rstSQL.Open q2, connB
When I try to open up this page in a browser, I get error message:
Microsoft OLE DB Provider for ODBC Drivers error '80040e37'
[DataDirect][ODBC Sybase Wire Protocol driver][SQL Server]#temp not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).
Could anyone please help me understand what the problem is and help me fix it?
Thanks.
With both queries, it looks like you are trying to insert into #temp. #temp is located on one of the databases (for arguments sake, databaseA). So when you try to insert into #temp from databaseB, it reports that it does not exist.
Try changing it from Into #temp From to Into databaseA.dbo.#temp From in both statements.
Also, make sure that the connection strings have permissions on the other DB, otherwise this will not work.
Update: relating to the temp table going out of scope - if you have one connection string that has permissions on both databases, then you could use this for both queries (while keeping the connection alive). While querying the table in the other DB, be sure to use [DBName].[Owner].[TableName] format when referring to the table.
your temp table is out of scope, it is only 'alive' during the first connection and will not be available in the 2nd connection
Just move all of it in one block of code and execute it inside one conection
temp is out of scope in q2.
All your work can be done in one query:
SELECT a.columnA, a.columnB,..., a.columnZ
FROM table2 a
INNER JOIN (SELECT databaseA..table1.column1
FROM databaseA..table1
WHERE databaseA..table1.xyz = 'A') b
ON a.columnB = b.column1