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.
Related
I have created a SQL Server stored procedure which contains insert and update statements and log table. When I execute the stored procedure locally using
EXEC stored_procedure_name param1
it works perfectly fine and logs entry is inserted into the log table; but when the same stored procedure is called from another server using the same SQL Server user, the stored procedure is called and correct output/response is going to calling server but insert and update statements are not executed and no logs are inserted.
Again, when I call the stored procedure locally, everything works. When I checked the entries in log table (with Id column as identity(1,1)), there are 2 entries with id 1 and 3.
I think entry with Id = 2 is inserted and then rollback as it called from another server.
I don't understand the different behavior. Please help.
Thanks in advance
ALTER PROCEDURE [dbo].[temp_procedure]
(#aid VARCHAR(MAX))
AS
BEGIN
SET NOCOUNT ON;
DECLARE #RETURN_CODE INT = -2;
DECLARE #RETURN_MESSAGE VARCHAR(MAX) = 'ENTITY NOT FOUND';
-- Check IF exist and Update
IF EXISTS (SELECT 1 FROM temp WHERE c = #aid)
BEGIN
UPDATE temp
SET a = 0, b = 0,
WHERE c = #aid;
SET #RETURN_CODE = 0;
SET #RETURN_MESSAGE = 'SUCCESS';
END
-- Log action and result in logging table for particular a_id
-- also has id column as identity
INSERT INTO [dbo].[Logs] ([A_Id], [Created_Date], [Return_Code], [Return_Message])
VALUES (#aid, GETDATE(), #RETURN_CODE, #RETURN_MESSAGE)
SELECT #RETURN_CODE AS 'RETURN_CODE', #RETURN_MESSAGE AS 'RETURN_MESSAGE';
END
I am currently working on getting a set of records from a view in the Oracle database and trying to insert/update them in to the table in the SQL Server table depending on a column using BizTalk.
For this I created a stored procedure:
Create PROCEDURE [dbo].[uspInsertorUpdateDepartment]
#dept_name varchar(64),
#jax_dept_id char(32)
AS
BEGIN
SET NOCOUNT ON;
IF (SELECT TOP (1) 1 FROM afm.[jax_dept]
WHERE jax_dept_id = #jax_dept_id) IS NULL
INSERT INTO afm.[jax_dept](dept_name, jax_dept_id)
VALUES (#dept_name,#jax_dept_id)
ELSE
UPDATE afm.[jax_dept]
SET dept_name = #dept_name
WHERE jax_dept_id = #jax_dept_id
END
I created the schema for the stored procedure using consume adapter service. Used them in the mapping and the orchestration. Though I was not able to use the lopping functoid in the mapping
So removed the lopping and deployed the application. And tried to run and it ran without any error but just insert the first record from the oracle view in to the SQL Server database leaving all the other records. How can this be approached so the entire set of records from the oracle is inserted/updated in to SQL Server database.
Here I converted the separate update and insert into one merge statement:
Create PROCEDURE [dbo].[uspInsertorUpdateDepartment]
#dept_name varchar(64),
#jax_dept_id char(32)
AS
BEGIN
SET NOCOUNT ON;
merge afm.[jax_dept] as target
using (select #dept_name as dept_name, #jax_dept_id as jax_dept_id) as source
on source.jax_dept_id = target.jax_dept_id
when matched then
update target
SET dept_name = #dept_name
when not matched then
insert (dept_name, jax_dept_id)
values (#dept_name,#jax_dept_id)
;
END
Use table type as a parameter for the SP, instead of passing individually. We can
use looping functoid if we use User Defined Table value as a parameter.
CREATE TYPE dbo.SampleType AS TABLE
(
dept_name varchar(64) not null,
jax_dept_id char(32) not null
)
---
Create PROCEDURE [dbo].[uspInsertorUpdateDepartment]
#TVP dbo.SampleType READONLY
AS
BEGIN
SET NOCOUNT ON;
--your insert or update query
For more infor on how to use table value parameter check out this link:-
https://learn.microsoft.com/en-us/sql/relational-databases/tables/use-table-valued-parameters-database-engine
I have a stored procedure called myStoredProcedure in SQL Server 2008 including a code block like this:
...
declare #tempTable table
(
Id int,
Name varchar(100),
Category varchar(50),
Volume int
)
while #startTime<#endTime
begin
insert into #tempTable
EXEC R52_Calculations #param1, #param2, #param3
set #startTime = DATEADD(YEAR,1,#startTime)
end
select * from #tempTable
In this way, the stored procedure is working very well. I can connect to a table to this stored procedure in the SSRS 2008 without any warning or error. However, when I change #tempTable variable into #tempTable like below, I am getting a TimeOut error when I try to connect a table on SSRS 2008 to the updated stored procedure, even though the stored procedure is working very well again in SQL Server.
...
create table #tempTable
(
Id int,
Name varchar(100),
Category varchar(50),
Volume int
)
while #startTime<#endTime
begin
insert into #tempTable
EXEC R52_Calculations #param1, #param2, #param3
set #startTime = DATEADD(YEAR,1,#startTime)
end
select * from #tempTable
This is the error:
Timeout expired. The timeout period elapsed prior to completion of
the operation or the server is not responding. Warning: Null value is
eliminated by an aggregate or other SET operation.
Some more points:
when I remove the "while" loop and do the process only 1 time, there is no error occurring when I use #tempTable.
if I use #temptable (variable one), there is no error occurring at all.
Note that both queries are working fine in SQL Server, the errors are occurring when I try to connect a table on SSRS 2008 to the stored procedure
.
I could not find the reason why #temptable is causing an error. Any clue or help I will appreciate. Thanks.
I have some procedures in database1 that are used to fill some tables using INSERT statements.
The tables I want to fill are in database2. How can I write a query with EXEC procedures in order to fill those tables?
I don't want to add stored procedures in the same database of the tables (database2)
This is one of the the stored procedures in db1
USE [database1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[AddSubject]
#SubjectCode nvarchar(20),
#Credits int,
#Hours int
AS
INSERT INTO [database2].[dbo].[Subject]
([Code]
,[Credits]
,[Hours])
VALUES
(#SubjectCode,
#Credits,
#Hours)
Return ##Identity
And here is where I execute the stored procedure:
EXEC #SubID = [database1].[dbo].[AddSubject] #SubjectCode='1234', #Credits=2, #Hours=50
And it gives me the error:
Msg 208, Level 16, State 1, Procedure AddSubject, Line 14
Invalid object name 'database2.dbo.Subject'.
You can refer to SQL Server tables with a four-part name:
server.database.schema.table
For a different database you only need the last three parts:
insert otherdb.dbo.yourtable
(col1, col2, ...)
values ('val1', 'val2', ...)
You can use this in a stored procedure to insert into a table in a different database.
Yes! you can acess the database2 into database1 for doing this both database should one server
If your scheema is dbo then you can access as below:-
Insert into database1..table_name (col1,col2)
select value1,value2
If your Scheema is other than dbo then :-
Insert into database1.Scheema_name.table_name (col1,col2)
select value1,value2
What are the best approaches to the below scenario?
In my C# program, I have some sql commands such as UPDATE, INSERT, DELETE. I could execute them in my C# program (which works fine) but I need to execute these sql commands when one of the stored procedure comes to the last line. So I am planning to store the sql commands in some staging table in the same database and then I would like to open this table within the stored procedure and execute one by one.
What is the best approach in terms of opening a table within stored procedure and then traversing through the table based on some condition (like select * from TempStagingTable where customerId = '1000'). If it returns 10 records, I would like to loop them and execute the sql command stored in a column named "CustomSqlScript"
PS: I am using SQL 2008 R2.
Well, you can select the data from table A initially, and instead of using cursor you can use while loop(as it will increase your performance compared to cursor) and then you can execute your predefined SQL statement from table B
Please find below sql scripts to do the same
Please note: I have not made use of any relation,This is just a plain example
CREATE TABLE test1(
customSqlScripts VARCHAR(100)
)
CREATE TABLE test2(
customer_Id INT PRIMARY KEY ,
first_Name VARCHAR(100),
last_name VARCHAR(100)
)
INSERT INTO test1 VALUES('Select first_Name from test2 where customer_Id=')
INSERT INTO test2 VALUES('1','Rohit','Tiwari')
DECLARE #Count INT
DECLARE #iCount INT=0
DECLARE #dummysql VARCHAR(100)
SELECT #Count= Count(*)
FROM test2
WHERE last_name='Tiwari'
WHILE(#icount<#count)
BEGIN
SELECT #dummysql =customSqlScripts
FROM test1
SET #dummysql=#dummysql+'1'
EXEC (#dummysql)
SET #icount=#icount+1
END