How to save stored procedure output into table - sql

I am new to T-SQL so I apologize if I am stating my question wrong.
I have a SQL Server stored procedure that has properties and returns integer value also selects some columns from different tables.
I was wondering how can I store that result into regular table
DECLARE #prop1 int;
DECLARE #prop2 int;
DECLARE #result int;
set #prop1 = 2
set #prop2 = 5
exec #result = dbo.Proc1 #prop1 #prop2
Result:
id name value
---------------------
1 Example 6
2 Process 8
.. ........ ..
Thank you in advance for all your input.
//-----------Edit 04/22/2015---------------------------
I am trying to use T-SQL below:
SELECT * INTO Tx.ReportFacts FROM OPENROWSET('SQLNCLI', 'Server=GCA_A;Trusted_Connection=yes;',
'SET NOCOUNT ON;SET FMTONLY OFF; EXEC #RC = ReportLibrary.Rpt.Server_GetAllDiscrepancies #FacilityKey ,#StationKeys ,#MedItemKeys ,#MedClassCodes ,#UserAccountKeys ,#ResolutionStatus ,#TransactionLimit ,#ReportStartDate ,#ReportEndDate')
-- Select Table
SELECT *
FROM Tx.ReportFacts;
But getting error below:
OLE DB provider "SQLNCLI11" for linked server "(null)" returned message "Deferred prepare could not be completed.".
Msg 8180, Level 16, State 1, Line 1
Statement(s) could not be prepared.
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#RC".
Can anyone point out why this is happening. And what is wrong with my T-SQL statement?

You can use insert - exec.
Try this:
insert into table_name
exec dbo.Proc1 #prop1 #prop2;

Related

How can I assign an exec result to multiple sql variables?

I got the returned data after executing a stored procedure named [s_sspCallSharePointWebService] in SSMS
DECLARE #sWebAddr AS NVARCHAR(MAX),
#bAPISuccess AS NVARCHAR(10),
#objSharePointXML AS XML
SET #sWebAddr = 'http://...'
EXEC [s_sspCallSharePointWebService] #sWebAddr, #bAPISuccess OUTPUT, #objSharePointXML OUTPUT
I was wondering how do I save
the data in variables instead of returning a table below.
---------------------------------------
| (No column name) | (No column name) |
---------------------------------------
| True | <XMLRoot>.... |
---------------------------------------
Additionally, I cannot insert the data into a temp table here because I had the result of EXEC sp_OAGetProperty #objecttoken, 'responseText' in [s_sspCallSharePointWebService], and then already inserted the response text into a temp table.
That would cause an error:
An INSERT EXEC statement cannot be nested
It is very ugly (for me), but this can be done using temporary tables. The temporary table is visible to all routines in the current scope.
So, you can have nesting like this:
EXEC SP1
...
EXEC SP2
...
EXEC SP3
...
and let's say EXEC SP2 is returning a row set executing a SELECT statement. So, the question is how to materialized it?
CREATE PROCEDURE dbo.SP1
AS
BEGIN;
SELECT 'SP1' AS [Caller];
EXEC dbo.SP2;
END;
GO
CREATE PROCEDURE dbo.SP2
AS
BEGIN;
SELECT 'SP2' AS [Caller];
INSERT INTO #TEST
SELECT 1;
END;
GO
CREATE TABLE #TEST
(
[ID] INT
);
EXEC dbo.SP1;
SELECT *
FROM #TEST;
The idea is to create the temporary table in the outer scope and the procedure to be sure that this table is already created and populate it. Then, use the table in the initial caller.
It's ugly for me, because if this table is not defined the routine will cause an error:
Msg 208, Level 16, State 0, Procedure dbo.SP2, Line 8 [Batch Start
Line 0] Invalid object name '#TEST'.
and it can be difficult to debug in some cases.
Instead of doing that, you can just use a table variable, and then SELECT from it to assign. Here's an example with a simple proc that returns a single row:
USE tempdb;
GO
CREATE OR ALTER PROC dbo.ReturnsOneRow
AS
BEGIN
SELECT 1 AS FirstColumn, 'Hello' AS SecondColumn, 4 AS ThirdColumn;
END;
GO
EXEC dbo.ReturnsOneRow;
GO
DECLARE #FirstColumn int;
DECLARE #SecondColumn varchar(20);
DECLARE #ThirdColumn int;
DECLARE #Row TABLE
(
FirstColumn int,
SecondColumn varchar(20),
ThirdColumn int
);
INSERT #Row
(
FirstColumn, SecondColumn, ThirdColumn
)
EXEC dbo.ReturnsOneRow;
SELECT TOP(1) #FirstColumn = r.FirstColumn,
#SecondColumn = r.SecondColumn,
#ThirdColumn = r.ThirdColumn
FROM #Row AS r;
-- Check the values
SELECT #FirstColumn, #SecondColumn, #ThirdColumn;
The table variable will be way better than a temp table in this situation, and you don't have issues with its visibility elsewhere, or having to clean it up (it's gone at the end of the batch).

Msg 30007, Level 16 dm_fts_index_keywords, dm_fts_index_keywords_by_document, dm_fts_index_keywords_by_property

I have a complex problem with sql server database, if anyone could help me, it would be great.
In my sql server 2014 express, i create a simple database with 3 tables :
"DocumentFile", "DocumentSearchTerm", "SearchTerm" and a full search text catalog FTCat including 3 columns of the "DocumentFile" table (ExtractText, FileNameWithoutExtension,FilePath)
And i've also created [Search] Store Procedure (and additional sql functions) to perform full search catalog.
(I share my sql server database backup : https://1drv.ms/u/s!AlUHN_KmzBqksIs9ylWc5eKBvF1Tgg in order to test)
When i run on my sql server express local this following script :
DECLARE #return_value int,
#TotalRecords int
EXEC #return_value = [dbo].[Search]
#SearchTerm = N'c++',
#CurrentPage = 1,
#PageSize = 20,
#TotalRecords = #TotalRecords OUTPUT
SELECT #TotalRecords as N'#TotalRecords'
SELECT 'Return Value' = #return_value
It runs well and it retunrs me 2 rows.
Now my problem is that i subscribed a smarterasp.net hosting plan including a sql server 2016 database with full search text catalog.
So i restored the backup on my hosted database (it run sucessfully), all the tables, stored procedures, functions and my full search text catalog was created successfully.
But now when i execute the same script :
DECLARE #return_value int,
#TotalRecords int
EXEC #return_value = [dbo].[Search]
#SearchTerm = N'c++',
#CurrentPage = 1,
#PageSize = 20,
#TotalRecords = #TotalRecords OUTPUT
SELECT #TotalRecords as N'#TotalRecords'
SELECT 'Return Value' = #return_value
It falied with following message error :
Msg 30007, Level 16, State 1, Line 20
Parameters of dm_fts_index_keywords, dm_fts_index_keywords_by_document, dm_fts_index_keywords_by_property, and dm_fts_index_keywords_position_by_document cannot be null.
Is anybody met this problem ?
Sql server throw an error and for me it's not normal , it must just return null.
I explain you what was the problem :
in my stored procedure [GetMainTags] , i writed the name of the dabase hardcoded (the old name of my sql server local) :
DECLARE #db_id int = db_id(N'semanticsdb');
So it's false. In my new database i must write :
DECLARE #db_id int = db_id(N'my_new_database_name');
and to be more generic i must do that for the current database whose execute the function :
declare #dbName varchar (100);
SELECT #dbName = DB_NAME();
DECLARE #db_id int = db_id(#dbName);

Insert results of a stored procedure into a temp table in SQL 2012 (The metadata could not be determined because every code)

I am stuck to insert reults from stored proc to temp table in SQL 2012, My old code is working perfectly on SQL 2008 but 2012 got that error.
Msg 11529, Level 16, State 1, Procedure sp_describe_first_result_set,
Line 1 The metadata could not be determined because every code path
results in an error; see previous errors for some of these.
Msg 4902, Level 16, State 1, Procedure sp_describe_first_result_set,
Line 1 Cannot find the object "#Tethys_ReportGenerator_Tbl" because it
does not exist or you do not have permissions.
My stored proc emit reults set which has dynamic columns, sometimes it has 10 and sometimes it has more 15 .Please help me out above issue.
My old code are given below also some code tried of 2012 is given below:
select a.* into [tempdb].[dbo].[tempBase]
from openrowset('SQLNCLI', 'Server=.;Trusted_Connection=Yes;Integrated Security=SSPI', 'SET NOCOUNT ON;SET FMTONLY OFF ; exec LIQ_TradeBustTrader5895.dbo.price_report #loginID = ''ALL'', #tableName = ''order_msgs'', #firmname = ''ALL'', #AssetClass = ''All'', #OutputBustRecords=0, #ManualOrder=0, #TimeFrom=''0:0'', #TimeTo=''23:59'', #ExcludeSimulatedTrades=0, #SingleTable =1 ') AS a;
For 2012
select a.* into [tempdb].[dbo].[tempBase]
from sys.dm_exec_describe_first_result_set (N'EXEC LIQ_TradeBustTrader5895.dbo.price_report #loginID = ''ALL'', #tableName = ''order_msgs'', #firmname = ''ALL'', #AssetClass = ''All'', #OutputBustRecords=0, #ManualOrder=0, #TimeFrom=''0:0'', #TimeTo=''23:59'', #ExcludeSimulatedTrades=0, #SingleTable =1', null, 2) AS a;

SQL - If Parameters within Stored Procedure

I am trying to get a complex stored procedure to work, but I can't figure out the relationship between stored procedures, parameters and IF/THEN statements.
I have stripped my code down to the attached chunk of code, that shows where I am going wrong. When I execute it, I get an error
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'and'
Basically, I have 3 variables - #Test1, #Test2 and #Test3. These are prompts that appear when you execute the stored procedure. If the user enters '1', '2', '3' respectively, it should show the text 'Show 1 and 2 and 3 Plus Pivot Section'. If the only enter '1','2' it should show the text 'Show 1 and 2 Plus Pivot Section'.
Below is my code, am I doing something wrong??
ALTER PROCEDURE [dbo].[sp_Data_Extract_Test]
#Test1 [NVARCHAR] (400),
#Test2 [NVARCHAR] (400),
#Test3 [NVARCHAR] (400)
WITH EXECUTE AS CALLER
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Output NVARCHAR(400) ;
Declare #param NVARCHAR(900) ;
Set #param = '#Test1 nvarchar(400), #Test2 nvarchar(400), #Test3 nvarchar(400)'
if (#Test1 = '1')
BEGIN
SET #Output = 'Show 1';
END
if (#Test2 = '2')
BEGIN
SET #Output = #Output + ' and 2';
END
if (#Test3 = '3')
BEGIN
SET #Output = #Output + ' and 3';
END
BEGIN
SET #Output = #Output + ' Plus Pivot Section'
PRINT #Output
END
EXECUTE SP_EXECUTESQL #Output, #param, #Test1, #Test2, #Test3;
END
Edit: My example above isn't a good example. I was trying to narrow it down to identify the problem, but it seems as though the Execute statement at the bottom expects a SQL statement, not a line of text.
What I am trying to do, is effectively the following. I want to execute a stored procedure that pivot's a data set. The data is built up by 2 appends (unions) that are based on prompts. I want it so that the user can potentially run it for 1 type of Quantity, for 2, or for 3. If they want to see all 3 Quantities, it needs to do 2 appends. The code is as below. I've added XXX's where the SQL statement is because I know those parts are working fine, it's only when I try to do this if statement based on variables so I can potentially filter off the unions.
--- Above: Alter Stored Procedure, with variable declarations
declare #V1 NVARCHAR(4000) ;
declare #param NVARCHAR(900) ;
set #param='XXXXXX'
if (#Value1 = 'Qty_Ordered')
BEGIN
set #V1='SELECT XXXXXX’
END
if (#Value1 = 'Qty_Ordered' and #Value2 = 'Qty_Supplied')
BEGIN set #V1= #V1 + '
UNION ALL
SELECT XXXXX'
END
if ((#Value1 = 'Qty_Ordered' or #Value2 = 'Qty_Supplied') and #Value3 = 'Qty_Forecast')
BEGIN set #V1= #V1 +
'UNION ALL
SELECT XXXXXX’
END
BEGIN
set #V1 = #V1 + '
PIVOT
(
SUM([Value])
FOR p.forecast_Week_No IN ('+#cols1+','+#cols2+','+#cols3+')) AS pvt'
END
EXECUTE SP_EXECUTESQL #V1, #param, XXXXXXXX;
END
The frist paramenter for sp_executesql should be a TSQL statement, but #Output does not represent that.
If your intention was only to print the message then comment EXECUTE
SP_EXECUTESQL #Output, #param, #Test1, #Test2, #Test3;
Now regarding Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'and'
sqlserver basically checked for syntax error in the TSQL stmt passed through #Output,
what it got was "Show 1 and 2 and 3 Plus Pivot Section"
As SHOW is not a SQL stmt, it considered it as a stored proc,
next it looked at 1, and 1 it is allowed as a paramenter
next it got "and", it is not accepted to used words like "and" while executing a SP
so gave a syntax error Msg 156, Level 15, State 1...

create trigger using a stored procedure

I have a trigger and I want to kick it off from a stored procedure. I am using ms access and when i run the trigger from ms access it gives me an error msg (ODBC). I think I can't create triggers using ms access. This is my trigger:
IF EXISTS
(SELECT name
FROM sys.objects
WHERE name = 'UpdateComments' AND type = 'TR')
DROP TRIGGER tblEmailHdr_abenit01.UpdateComments;
GO
CREATE TRIGGER UpdateComments
ON tblEmailHdr_abenit01
AFTER Update
AS
IF ( UPDATE (Comments) ) BEGIN Update ttblEmailHdr_abenit01
Set UpdateComm = GetDate()
END;
GO
This is how I have been trying to create the trigger from the stored procedure but I get the following error msg's when I try to create the sproc:
Sproc:
CREATE PROCEDURE dbo.SP_AS_tblEmailHdr_Trig (#UserID as varchar(10))
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
--SET NOCOUNT ON;
-- Insert statements for procedure here
Declare #UserTable Varchar(50)
Declare #UserTable2 Varchar(50)
Set #UserTable = 'tblEmailHdr_' + #UserID ;
Set #UserTable2 = 'tblEmailHdr_' + #UserID + '.UpdateComments' ;
IF EXISTS
(SELECT name
FROM sys.objects
WHERE name = 'UpdateComments' AND type = 'TR') DROP TRIGGER #UserTable2
GO
CREATE TRIGGER UpdateComments
ON #UserTable
AFTER UPDATE
AS
IF ( UPDATE (Comments) )
BEGIN
--RAISERROR (50009, 16, 10)
Update #UserTable
Set UpdatedComm = GetDate()
END
GO
END
GO
error msg i get:
Msg 102, Level 15, State 1, Procedure SP_AS_tblEmailHdr_Trig, Line 23
Incorrect syntax near '#UserTable2'.
Msg 102, Level 15, State 1, Procedure UpdateComments, Line 2
Incorrect syntax near '#UserTable'.
Msg 1087, Level 15, State 2, Procedure UpdateComments, Line 8
Must declare the table variable "#UserTable".
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'END'.
create procedure pro (parameters)
as
begin
declare #trigs nvarchar(max)
declare #trip nvarchar(max)
set #trigs='
create trigger tri on dbo.employee
for insert
as
select * from inserted
go'
set #trip='drop trigger tri'
EXEC sp_executeSQL #trigs
insert into employee values(parameters)
EXEC sp_executeSQL #trip
end
exec pro param
eg:
exec pro 80,'aaa','AAS',25000,'2013-02-01','iT'
remove all the GO statements from inside the procedure.