I have a stored procedure that stores values in temp tables.
It all works well, but I can not bcp it with
exec master..xp_cmdshell 'bcp "exec sp_test '2006-07-21' " queryout c:\test.txt -c '
If I change the table to regular, then it all works. Can you not use temp tables this way?
I would not necessarily want to share the code as it contains company stuff, but it is basically like this
SELECT
*
INTO #Extractr
FROM
TABLE A
WHERE ID in (4,9,14)
The error message is invalid object #Extractr
Thanks!
I have just stumbled upon this a few days ago.
What I've learned from this link:
http://www.dbforums.com/microsoft-sql-server/1605565-can-we-have-temporary-table-store-procedure-when-using-bcp.html
is that it won't see temp tables as they'd be in the tempdb database not the one you are using.
Also, I got mine working by replacing the local temp tables to global ones (## instead of # with a simple replace helped me).
As #Kevin has mentioned in the comments, you can alternatively use table variables for the same purpose.
Hope this will work for you.
Have you tried referencing the temp table like this in your query: tempdb..#Extractr
For example:
SELECT
*
INTO tempdb..#Extractr
FROM
TABLE A
WHERE ID in (4,9,14)
Using table variables instead of temp tables helped me to figure it out.
DECLARE #tbl1 TABLE
(fld1 int,...)
INSERT INTO #tbl1
SELECT * FROM Table1
Related
I am creating a SQL Query dynamically. After it's been created I want to execute it and store it as a temporary table.
WITH [VALIDACCOUNTS] AS( EXEC (#sqlQuery))
You have two solutions for this:
As a first solution you can simply use an INSERT EXEC. This will work if you have a specified result set. This could be used if your procedure just returns one result set with a fixed result design.
Simply create your temporary table with matching columns and datatypes. After that you can call this:
INSERT INTO #yourTemporaryTable
EXEC(#sql)
The second solution would be the usage of OPENROWSET for this, which may have some sideeffects.
You can read more about it here.
INSERT INTO #yourTemptable
SELECT *
FROM OPENROWSET('SQLNCLI', 'DRIVER={SQL Server};',
'EXEC (''+#sql+''))'
EDIT: The things I've tried below came directly from the alleged duplicate. The solutions actually do work fine with a user defined sp (and probably most system sp's), but for whatever reason it doesn't work with this one.
I can run exec sp_showpendingchanges on the distribution publication database without any issues. However I want to capture the results in a table
I've tried:
SELECT * INTO #tmpTable
FROM OPENROWSET('SQLNCLI', 'Server=SERVER; Trusted_Connection=yes;',
'EXEC sp_showpendingchanges')
and:
SELECT * INTO #tmpTable
FROM OPENQUERY(SERVER, 'exec sp_showpendingchanges')
Both of these statements return an error that says: Invalid object name 'sysmergepublications'.
I tried to specify the initial catalog in the connection string and even tried adding a USE statement in the last parameter of each statement (i.e. I used an embedded EXEC statement with double-single quotes and all that). But I still end up with the same error.
So how can I get the results from exec sp_showpendingchanges into a temporary table, and preferably without having to define the table myself? If all else fails I will make a program in C#, but really hoping there's a simpler way to just do this with just SQL.
Here is a working example
You create a table
DECLARE #result_table TABLE
(
destination_server SYSNAME ,
pub_name SYSNAME ,
destination_db_name SYSNAME ,
is_dest_subscriber BIT ,
article_name SYSNAME ,
pending_deletes INT ,
pending_ins_and_upd INT
)
execute the script
INSERT INTO #result_table
EXEC sp_showpendingchanges
view the results
SELECT * FROM #result_table
I read your question but definetly cannot understand what the problem to create temp table. Anyway, if you can execute SP but get an error when you do it through linkedserver or openrowset - than problem is in permissions.
Check permissions on sysmergepublications table. If user, which you use for linked server or openrowset, has no grant on do select this table you need to add this permission to user.
I hope it will help you.
I've got a very basic SQL query that I'd like to be able to view in R.
The trouble is, I need to be able to reference a #table:
select
RAND(1) as random
into #test
select * from #test
Is this possible, or will I need to create permanent tables, or find some other work around?
I currently do this via a RODBC script which allows me to choose which SQL file to run:
require(RODBC)
sql.filename <- choose.files('T:\\*.*')
sqlconn <- odbcDriverConnect("driver={SQL Server};Server=SERVER_NAME;Trusted_Connection=True;")
file.content <- readLines(sql.filename)
output <- sqlQuery(sqlconn, paste(file.content[file.content!='--'],collapse=' '))
closeAllConnections()
Do you have any advice on how I can utilise #tables in my SQL scrips in R?
Thanks in advance!
When you use temp tables SQL outputs a message with the number of rows in the table. R doesn't know what to do with this message. If you begin your SQL query with SET NOCOUNT ON SQL will not output the count message.
I use #tables by separating my query into two parts, it returns character(0) if I do like:
sqlQuery(test_conn, paste("
drop table #test;
select
RAND(1) as random
into #test
select * from #test
"))
So instead I would use:
sqlQuery(test_conn, paste("
drop table #test;
select
RAND(1) as random
into #test
"))
sqlQuery(test_conn,"select * from #test")
It seems to work fine if you send one Query to make the #table, and a second to retrieve the contents. I also added in drop table #test; to my query, this makes sure there is not already a #test. If you try to write to a #table name that is already there you will get an error
I am trying to combine the results of xp_cmdshell with a select query.
I have tried union & read about creating a temp table, but as my result will be having only 1 column. To be more precise i need a smaller query to combine the results of xp_cmdshell with select query as am trying to use it in union based sql injection
For example:
Select name from employee
union
exec xp_cmdshell 'whoami'
I know this wont work but somewhat similar would be great :)
You should know what this stored procedure returns and what outputs. Then when you know the table schema this procedure returns you may use the following syntax:
DECLARE #procedureOutput nvarchar(max)
SET #procedureOutput=Exec xp_cmdshell 'dir'
SELECT name FROM employee union #procedureOutput
If you need convert two different data types, CAST and CONVERT commands are for you.
Create a temp table and do insert into #temp EXEC.. or use OPENROESET. Refer this
http://beyondrelational.com/modules/2/blogs/70/posts/10812/select-columns-from-exec-procedurename-is-this-possible.aspx
I am executing a SP within a SP. The SP returns say 10 params. I am interested in only 5 of them. How do I insert only these 5 into the temp table.
The code I have so far:
DECLARE #tmpUnion TABLE
(
UnionCode VARCHAR(10),
UnionDate DATETIME,
UnionPosition VARCHAR(30),
UnionInitFees BIT,
UnionDues BIT
)
--getDetails returns 10 params. I need only these 5
INSERT INTO #tmpUnion
(UnionCode, UnionDate, UnionPosition, UnionInitFees, UnionDues)
EXEC getDetails
#iUserId = #OriginalLoginId
Put the result of getDetails into a tablevar that contains all of the return values, then do your insert off of the additional table.
You might also check out this site for more information on how to share data between stored procedures.
Use OPENROWSET like so:
Select
*
from OPENROWSET('SQLOLEDB','Data Source=Server_name;Trusted_Connection=yes;
Integrated Security=SSPI','Execute yourdb..get_orders')
Now you can easily filter the resultset
Select
employeeid,orderid,orderdate
from
OPENROWSET('SQLOLEDB','Data Source=Server_name;Trusted_Connection=yes;
Integrated Security=SSPI','Execute yourdb..get_orders')
where
orderdate>='19960101' and orderdate<'19970101'
You don't need to create a temp table and you also don't need to worry about the structure of the procedure.
Found here
EDIT: Final solution moved from comments after discussion.
You can't. The table variable must match exactly the structure of waht is being returned.