TSQL insert exec(#command) - sql-server

I am wondering why below statement is not working:
insert into #temp (ip, ping) values ('ip', exec xp_cmdshell 'ping ip')
I would like to get resultset where I will have ip address in one column and ping from that server. Above query returns errors:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'exec'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ')'.
Thanks in advance for explanations.

You can't execute anything in a INSERT statement value list. You need to execute like this:
insert into #temp
execute xp_cmdshell 'ping ip'
[This assumes that the #temp table has a column structure matching the resultset of xp_cmdshell ]
You can also create an intermediate temp table to contain all the columns that the stored procedure returns and then insert just the ones you want into your final table.

Well, insert ... exec is notoriously inflexible. For one thing, it won't work with a values clause. Even more annoyingly, it does not support a column list. The columns in the table have to match the output of the stored procedure exactly.
The only way to use insert ... exec is:
insert TableName exec(...)
-- ^^^--> no column list!
Here's an example:
if exists (select * from tempdb.sys.tables where name like '#temp__%')
drop table #temp
create table #temp (output varchar(max))
insert into #temp execute xp_cmdshell 'ping pong'
select * from #temp

Related

Insert Temp Table Failing with Parsing Error on Exec

I want to insert the result set coming from a query into a temporary table in Azure SQL Data Warehouse. I used the below statements but I am getting a parse error:
DECLARE #SQL2 NVARCHAR(1000)
CREATE taBLE #TempTable (L NVARCHAR(100))
SET #SQL2 = 'SELECT Col1 FROM Table1'
INSERT INTO #TempTable (L) EXEC SQL2***
Msg 103010, Level 16, State 1, Line 44
Parse error at line: 5, column: 28: Incorrect syntax near 'EXEC'.
I even tried Declare #T TABLE (ID iNT) still getting a parse error.
I got answer minutes after uploading the question
Azure SQL Data Warehouse does not support INSERT ... EXEC
For explanation and an alternative approach: https://learn.microsoft.com/en-gb/azure/sql-data-warehouse/sql-data-warehouse-develop-stored-procedures#insertexecute

Insert stored procedure data in a temp table in SQL Server

I am trying to insert the data of a stored procedure into a temp table like below
CREATE TABLE #CustomTable3HTML
(
ItemId varchar(30),
ItemId1 varchar(30)
)
INSERT INTO #CustomTable3HTML
EXEC SalesDeals.dbo.prGetDealProposalDetail 17100102, 1
but I am getting this error
Msg 8164, Level 16, State 1, Procedure prGetDealProposalDetail, Line 138 [Batch Start Line 1]
An INSERT EXEC statement cannot be nested.
I figured this is because the stored procedure already has an insert into clause defined and I found out that it can be used only once in the calling chain.
So I started looking for other options and found out about OpenRowSet which I am using as below
SELECT *
INTO #CustomTable3HTML
FROM OPENROWSET('SQLOLEDB','Server=Demo\Demo;Trusted_Connection=Yes;Database=SalesDeals',
'SET NOCOUNT ON;SET FMTONLY OFF;EXEC SalesDeals.dbo.prGetDealProposalDetail 17100102,1')
I am getting an error when I run this SQL command
Access to the remote server is denied because no login-mapping exists.
It works fine when I use a higher level account like sysadmin but fails with the other account which is a normal db owner on the database where I am running this SQL.
There is work around of this. It's not beautiful, but it will work.
In our outer query define a table:
CREATE TABLE #CustomTable3HTML
(
ItemId varchar(30),
ItemId1 varchar(30)
)
Change the procedure adding the following code at the end:
IF OBJECT_ID('tempdb..#CustomTable3HTML')
BEGIN
INSERT INTO #CustomTable3HTML
SELECT ....
END
ELSE
BEGIN
SELECT ....
END
After executing the stored procedure you will have the data in table.

Incorrect syntax near the keyword “AS” when alter trigger

i created trigger called trgInsteadofdeleteEmp
and i just want to alter it, i wrote the following SQL code
alter trigger trgInsteadofdeleteEmp on Emp
instead of delete
as
begin
declare #id int , #name nvarchar(100)
select #id =id from deleted
select #name = name from deleted
insert into EmployeeAudit values (#id ,#name + 'tried to delete at' + GETDATE() as varchar(50))
end
and have the following output:
Msg 156, Level 15, State 1, Procedure trgInsteadofdeleteEmp, Line 8 Incorrect syntax near the keyword 'as'.
can someone point me in the direction of how to find the error
Thanks.
No, no, no, no, no.
Don't make the mistake of assuming that inserted and deleted have only one row. You are just putting errors in your code that are going to pop up at an unexpected time. I actually wish that SQL Server flagged this usage when creating the trigger.
Instead:
alter trigger trgInsteadofdeleteEmp on Emp
instead of delete
as
begin
insert into EmployeeAudit(id, name)
select id,
name + ' tried to delete at ' + convert(varchar(255), GETDATE(), 121) )
from deleted d;
end;
Your error is caused by the as. There seems to be a missing cast() function. But that is not the right fix. With date/times, use convert() or format() along with the desired format.
Other suggestions:
Always include the column names when doing an insert. In fact, an audit table really should have an identity id column, createdBy, and createdAt columns, all with default values.
Look at the strings that will be produced and be sure they are readable.
Use semicolons to end statements.
Don't rely on default formatting for date/time values.

Return Stored Proc Results in CTE

Is it possible for me to call a stored proc into a CTE. I have a login to our reporting DB that is only RO. I have write access to our UAT but would like to query live data.
So can I use a stored proc in a CTE?
with clientOwes as (
exec des_Batch_GetApplicationClientOwesList
)
select a.des_applicationnumber
from des_heapplicationset a
where a.des_heapplicationid in (select applicationid from clientowes)
result was: Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'exec'.
Answer adapted from dialogue in comments:
You can use a stored procedure to populate a table variable, which Read Only access does allow you to create. You won't need to use OpenRowSet to populate it either. Just do:
INSERT INTO #MyTableVariable
EXEC MyStoredProcedure
I do this in a lot of places myself where I need to treat Stored Proc results as a table that I can JOIN or UNION with other tables.

Invalid column name "USER_SOURCE"

I have a stored procedure which is returning a result in an xml #Data output parameter
To assign data in xml code is
SELECT #data= (
SELECT DISTINCT
CONVERT(varchar(2),u.USER_SOURCE ) + '~' +
CONVERT(varchar(20), u.[USER_ID]) + '-' +
CONVERT(varchar(10), u.DEALER_ID) as USER_DEALER_ID
FROM #users u FOR XML RAW('users'))
When I exec the procedure in SQL Server Mgmt Studio, I can see the result OK.
This procedure is been called from another procedure, and that parent procedure is used in SSRS.
In SSRS I am getting error
Query execution failed for dataset 'DataSet1'. Invalid column name
'USER_SOURCE'. Invalid column name 'USER_ID'. Invalid column name
'DEALER_ID'.
Could you please help?
Thanks,
Chetan
Here's a script which I think reproduces a problem identical to yours:
CREATE PROCEDURE TestTmpTable
#value varchar(20)
AS
BEGIN
CREATE TABLE #test (id int IDENTITY, value varchar(20));
INSERT INTO #test (value) VALUES (#value)
SELECT * FROM #test;
DROP TABLE #test;
END
GO
CREATE TABLE #test (id int IDENTITY, value2 varchar(20));
EXEC TestTmpTable 'some text';
SELECT * FROM #test;
DROP TABLE #test;
GO
DROP PROCEDURE TestTmpTable
As you can see, there are two #test tables here, one is created in the stored procedure, the other one in the batch that invokes the stored procedure. They have different structures: one has a column named value, the other a column named value2. If you run the script, you'll see this error:
Msg 207, Level 16, State 1, Procedure TestTmpTable, Line 6
Invalid column name 'value'.
I can't point you to a relevant documentation article at the moment, but to me it is evident enough that some preliminary name checking is taking place immediately before the execution of the SP. At that stage, a discrepancy between the column names referenced in the stored procedure and those actually present in the already existing table is revealed, which renders the execution impossible.
If you change value2 to value, the script will work without any problem, and there will be two row sets in the output, one with the 'some text' value, the other empty. And of course the script will work if you remove all parts related to the external #test table.
So, check the places where your procedure is called to see if any other #users table can be existing by that moment, and if so, amend the issue according to your situation.

Resources