SQL Server : how to get specific column from stored procedure without modifying it - sql

Here is the sample stored procedure
DECLARE #ReturnTable TABLE (DateTime DATETIME,
WrongUSSD VARCHAR(30),
AllMSISDN INT,
UniqueMSISDN INT,
SubscriptionActivated INT)
SELECT *
FROM #ReturnTable
Modification in stored procedure is not allowed, I just need specific column form this procedure by select statement.
I have tried this
select WrongUSSD
FROM openrowset('MSDASQL', 'Driver={SQL SERVER}; Server=server_name;UID=user; PWD=pass;Trusted_Connection=yes;', 'EXEC [DatabaseName].[dbo].[ProcedureName] "2016-01-01","2016-04-01"') as a
This method doesn't work if the is link server exists in stored procedure
Is there any other method?? Please help

Using temp table:
INSERT INTO #TempTable
EXEC [dbo].[ProcedureName]
SELECT WrongUSSD
FROM #TempTable

Related

Inserting into a user-defined table type via a dynamic query in SQL Server?

I have a user-defined table type tyAnalysisNumbers. I need to populate my user defined data type within a stored procedure with a SELECT statement and I am struggling to get that working within my stored procedure.
The following ways I have tried do not work
DECLARE #MyTable tyAnalysisNumbers;
INSERT INTO #MyTable
EXEC ('SELECT * FROM ' + #someTable);
I get this error:
An INSERT EXEC statement cannot be nested
I am unsure how to insert into my custom table via a select statement.
Can anyone help me accomplish this?
An INSERT EXEC statement cannot be nested
Above error is self explanatory. Please look at below scenario:
For example, we have one procedure which inserts data in table type and return result.
CREATE PROCEDURE uspInsertData1
AS
BEGIN
DECLARE #MyTable tyAnalysisNumbers;
INSERT INTO #MyTable
EXEC ('SELECT * FROM someTable');
select * from #MyTable
END
Now, let's say we have another procedure which will call above procedure and again insert data in another table.
CREATE PROCEDURE uspInsertData2
AS
BEGIN
DECLARE #MyTable tyAnalysisNumbers;
INSERT INTO sometable
EXEC uspInsertData1
END
Now, if you execute 1st procedure it will work fine but if you execute second procedure you will get this error.
An INSERT EXEC statement cannot be nested.
Because now you have nested EXEC statements.
I suggest to finish your work in single stored procedure if possible.
Try it like this:
DECLARE #MyTable tyAnalysisNumbers;
SELECT * INTO #Temp FROM #MyTable;
DECLARE #tblName AS SYSNAME = (SELECT name FROM sys.tables WHERE name = #someTable);
EXEC ('INSERT INTO #Temp SELECT * FROM ' + #tblName);
This also addresses the SQL Injection problem.

Select specific columns from the stored procedure

I have a stored procedure in other database which is maintained by other team. Assume that it is currently returning 3 columns, and my system only needs those 3 columns
but the other team can add few more columns for their own use which is causing my system to fail.
Other database SP
ALTER PROCEDURE FirstSP
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE #A (Id INT, Name VARCHAR(200), Amount VARCHAR(100), TestColumn INT)
INSERT INTO #A VALUES
(1,'ABC','23',1), (2,'CDF','35454',2), (3,'hjhj','9809909',3)
SELECT * FROM #A
DROP TABLE #A
END
GO
And below is my query, which was only expecting 3 columns from the source
CREATE TABLE #MyTable (Id INT, Name VARCHAR(200), Amount INT)
INSERT INTO #MyTable
EXEC dbo.FirstSP;
SELECT * FROM #MyTable
DROP TABLE #MyTable
Is there any way I can provide the column list?
This is what I am trying but it seems that I can't use server name as the parameter
DECLARE #ServerName VARCHAR(100) = ##SERVERNAME
SELECT * FROM OPENQUERY(#ServerName,'EXEC dbo.FirstSP')
My whole problem is to just select required columns from the SP. SP can have many columns in future.
Try this:
/*
-----------------------------------------------------------------------
Replace <SERVERNAME>\<INSTANCENAME>], <DATABASENAME> with your names
*/ ------------------------------------------------------------------------
-- First, enable Data Access (One time only)
EXEC sp_serveroption '<SERVERNAME>\<INSTANCENAME>', 'DATA ACCESS', TRUE;
-- Then SELECT just the fields you need
SELECT ID, Name, Amount
FROM OPENQUERY([<SERVERNAME>\<INSTANCENAME>], 'EXEC <DATABASENAME>.dbo.FirstSP')
I would ask the team that develops the stored procedure to create a parameter "Team" or something and slightly change the sp so that it will return the expected columns based on this parameter.
A more cumbersome solution is to use this stored procedure the get the colum names of the (first) result returned by the sp.
sp_describe_first_result_set 'dbo.usp_mySp';
And then use the result to create some dynamic SQL.

Get SQL Server remote procedure result

I have 2 SQL Server 2005, I want to pull data from A to B.
I execute this code on B.:
create table #res (
ValueID int,
[Timestamp] varchar(32),
RealValue float,
Quality int,
Flags int
);
insert into #res(ValueId, [Timestamp], [RealValue], [Quality], [Flags])
exec ('exec [CC_ExternalBrowsing].[dbo].[cc_sp_readtags] #List=''1;2;3;4;5'', #TimeBegin=''0000-00-00 00:05:00.000'', #TimeEnd=''0000-00-00 00:00:00.000''') AT [WINCCTESZT]
select * from #res;
drop table #res
Exec part runs fine (without the previous insert line). I can see data in SSMS, but I can't insert data into the temp table
I get this error:
The procedure 'sys.addlinkedserver' cannot be executed within a transaction.
Any ideas?
Thanks
Zui
Use a table-valued variable instead of the explicit Temp table - as table-creation cannot occur within a transaction. Try this instead:
declare #res table (
ValueID int,
[Timestamp] varchar(32),
RealValue float,
Quality int,
Flags int
);
insert into #res(ValueId, [Timestamp], [RealValue], [Quality], [Flags])
exec ('exec [CC_ExternalBrowsing].[dbo].[cc_sp_readtags] #List=''1;2;3;4;5'', #TimeBegin=''0000-00-00 00:05:00.000'', #TimeEnd=''0000-00-00 00:00:00.000''') AT [WINCCTESZT]
select * from #res;
-- drop table #res -- no longer needed

Execute store procedure like a "table" for SELECT operator (MS SQL SERVER)

Is it possible to execute store procedure
like a "table" for SELECT operator (MS SQL SERVER)?
Something like
SELECT TotalSum FROM exec MyStoreProcedure '2011/11/01', '2011/11/01'
I mean somehow integrate it into the SELECT operator?
Thank you!
Thanks guys!
The solution what I did is based on your answers:
declare #result table (f1 varchar(20),f2 varchar(20), CodProducto int, NomProducto varchar(1000), Costo decimal, Cantidat int, Total decimal)
INSERT INTO #result exec MyStoreProcedure '20111201', '20111201'
select * from #result
I supposed your proc returns several columns and you just want one, right?
small workaround is to add the result of the proc to a table variable and then select from it
create proc proc1 as
select 1 as one, 2 as two
declare #result table (one int, two int)
insert into #result
exec proc1
select one from #result
This would be better as a function rather than a stored procedure.
create function dbo.TestTable
(#var1 bit)
returns table
AS
RETURN
( select *
from INFORMATION_SCHEMA.TABLES
where #var1 = 1
);
select * from
dbo.TestTable(1)
Not directly (or without altering the stored procedure to be a table-valued function).
But you could do this:
INSERT INTO SomeTempTableWithSchemaMatchingTheSproc (...)
EXEC MyStoredProcedure
SELECT * FROM SomeTempTableWithSchemaMatchingTheSproc
SQL Server 2005 onwards, you can also use a table variable.
This works for me:
CREATE VIEW dbo.vw_xxx
AS
select * from openquery(YOURSERVERNAME, 'exec [sp_xxx] '''','''','''','''','''','''' ')

How to query from a stored procedure in SQL Server?

Let say I have a simple Stored Procedure:
ALTER PROCEDURE [dbo].[myProc]
AS
BEGIN
SELECT * FROM myTable
END
How can I do a WHERE statement in Microsoft SQL Server Management Studio to the stored procedure? Something like that:
SELECT * FROM myProc WHERE x = 'a'; -- But that doesn't work...
It sounds like you're trying to make a "dynamic" stored procedure.
Something you might want to do is:
1) Insert the contents of your stored procedure into a temporary table
2) Use dynamic sql to apply a where condition to that temporary table.
Something like:
declare #as_condition varchar(500); --Your condition
create table #a
(
id bigint
)
insert into #a
execute sproc
declare #ls_sql varchar(max);
set #ls_sql = "select * from #a where " + #as_condition;
execute (#ls_sql);
SQL Server allows you to use INSERT INTO to grab a stored procedure's output. For example, to grab all processes with SPID < 10, use:
create table #sp_who (
spid smallint,
ecid smallint,
status nchar(30),
loginame nchar(128),
hostname nchar(128),
blk char(5),
dbname nchar(128),
cmd nchar(16),
request int)
insert into #sp_who execute sp_who
select * from #sp_who where spid < 10
You can't add a WHERE clause to a stored procedure like this.
You should put the clause in the sproc, like this:
ALTER PROCEDURE [dbo].[myProc]
#X VARCHAR(10)
AS
BEGIN
SELECT * FROM myTable WHERE x=#X
END
GO
The syntax for calling a stored procedure is through the use of EXECUTE not SELECT(e.g.):
EXECUTE dbo.myProc 'a'
I think you can't do that.
The command to execute a stored procedure is EXECUTE.
See some more examples of the EXECUTE usage.
I think its better to use a view or a table valued function rather than the suggested approach. Both allow you to pass parameters to the function
If you want the WHERE clause to be something you can "turn off" you can do this, passing in a predetermined value (e.g. -1) if the WHERE limitation is to be bypassed:
ALTER PROCEDURE [dbo].[myProc]
#X VARCHAR(10)
AS
BEGIN
SELECT * FROM myTable WHERE x=#X or #X = -1
END
GO
You must declare a variable in the store procedure which will be necessary to pass to run the stored procedure. Here is an example. Keep this in mind: Before AS you can simply declare any variable by using the # character, but after the AS you must write Declare to declare any variable, e.g., Declare #name nvarchar (50).
ALTER PROCEDURE [dbo].[myProc]
#name varchar (50)
AS
BEGIN
SELECT * FROM myTable
where name= #name
END