Combine sp result in select as column - sql

I am trying to execute sp as sub query and treat result set of sp as column of outer query . Some thing like this
Select U.FirstName , (exec SomeSP ) as columnFromSP from User U
Is this possible i searched alot but found nothing on google.
Update
I cannot use #temp table because i am trying to do without #temp table

If you are able to convert your USP to a table value UDF, you will be use the UDF in your FROM statement.
CREATE FUNCTION dbo.SomeUDF
(
-- Add the parameters for the function here
#param varchar(1000)
)
RETURNS TABLE
AS
RETURN
(
SELECT #param as Value
)
GO
SELECT
a.Value,
'B' as Value2
FROM dbo.SomeUDF('ABC') a

Not possible, but you can work around it
Create a temp table & insert the results of the procedure into
it
Now join the User table with the temporary table and select the
columns you want from both tables
This assumes however, you have a joinable expression returned from the stored proc (one that you can match to a field in the user table). If the stored procedure on returns a single row, use a condition of 1=1 or something similar

-- Declare a temp table and column(for eg you have only 1 column)
CREATE TABLE #TEMP
(
FirstName VARCHAR(50)
)
-- The results after execution will be inserted to this table
INSERT INTO #TEMP
Exec SomeSP 'Params'
-- Select records from both tables in all combinations
SELECT U.FirstName , COL1 as columnFromSP
from User U
CROSS JOIN #TEMP

Related

How to declare an array in SQL server query and how to assign value into this array from other select query

ALTER PROCEDURE [dbo].[createTimeFrameReport]
AS
--BEGIN TRAN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--declare #currentYear varchar (4)
--declare #currentMonth varchar(3)
--declare #currentDay varchar(3)
DECLARE #applicationNo varchar(20);
TYPE ListofIDs IS VARRAY(100) OF NUMBER;
//how to assign value for below code a.APPLICATION_ID into an array
SELECT #ListofIDs =a.APPLICATION_ID from BPM_PROCESS_INSTANCE a,BPM_TASK_INSTANCE b,BPM_PROCESS c where b.PROCESS_INSTANCE_ID=a.ID and c.ID=a.TYPE_ID and a.TYPE_ID=42
AND b.ASSIGNED_ROLE IN('IDB_Reviewer','IFP_TechReviewerPermitting','IFP_ProcessManager','IFP_TechReviewerAssessment')
select #ListofIDs
In SQL there is not Array variable, however some SQL features replaces the logic of that array, it depend on how you use it, and i think what you are looking for is Temporary Tables
how to create temporary tables ? , to create temp table you need to have a hashtag sign # before the name of the temp table. see sample below (2 ways to create temp table
Using CREATE TABLE
CREATE TABLE #testTempTable
(
Column1 DataType,
Column2 DataType,
Column3 DataType,
etc...
)
Using SELECT INTO #testTempTable
SELECT Column1, Column2, Column3
INTO #testTempTable
FROM SourceTableNameHere
There is also called Variable Table in SQL , you can google it to know how to use it.
NOTE: it is best practice to drop the temporary table at the end of the script to avoid errors when the script contains temp table runs in the 2nd time.
sytanx:
DROP TABLE #testTempTable
Hope it helps.
SQL Server has not array type but you can use table variables or temp tables instead.
Also please don't use outdated comma syntax, use JOIN ON instead.
TEMP TABLE:
SELECT a.APPLICATION_ID
INTO #ListofIDs
FROM BPM_PROCESS_INSTANCE a
JOIN BPM_TASK_INSTANCE b
ON b.PROCESS_INSTANCE_ID = a.ID
JOIN BPM_PROCESS c
ON c.ID = a.TYPE_ID
WHERE a.TYPE_ID = 42
AND b.ASSIGNED_ROLE IN('IDB_Reviewer',
'IFP_TechReviewerPermitting',
'IFP_ProcessManager',
'IFP_TechReviewerAssessment');
SELECT #ListofIDs;
TABLE VARIABLE:
DECLARE #ListofIDs TABLE
(
APPLICATION_ID int
);
INSERT INTO #ListofIDs(APPLICATION_ID)
SELECT a.APPLICATION_ID
FROM BPM_PROCESS_INSTANCE a
JOIN BPM_TASK_INSTANCE b
ON b.PROCESS_INSTANCE_ID = a.ID
JOIN BPM_PROCESS c
ON c.ID = a.TYPE_ID
WHERE a.TYPE_ID = 42
AND b.ASSIGNED_ROLE IN('IDB_Reviewer',
'IFP_TechReviewerPermitting',
'IFP_ProcessManager',
'IFP_TechReviewerAssessment');
SELECT #ListofIDs;

SQL Server - Call stored procedure in a IN Statement [duplicate]

This question already has answers here:
How to SELECT FROM stored procedure
(14 answers)
Closed 8 years ago.
First of all, is it even possible ?
I have a stored procedure which looks like:
SELECT this FROM table WHERE this IN (SELECT that FROM another_table WHERE that = #Param)
I would like to replace (SELECT that FROM another_table WHERE that = #Param) by another stored procedure
I am having trouble finding the right syntax to make it work. I tried:
SELECT this FROM table WHERE this IN (EXEC new_stored_procedure #Param)
But this doesn't work. Does somebody know the right syntax to do so ?
Thank you for helping
You can create a temporary table
-- match exact columns with datatype returned from the stored procedure
create table #temp(col1 int, col2 .... )
insert into #temp(col1,...)
EXEC new_stored_procedure #Param
SELECT this FROM table WHERE this IN (select col from #temp)
You can use a Table-Valued Function
CREATE FUNCTION [dbo].[Get10Companies]
(
#DepartmentId Int
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
SELECT TOP (10) ID from company
WHERE DepartmentId = #DepartmentId
)
SELECT * from ( Select * from Get10Companies (1104)) t

SQL query for finding all tables ROWS with two columns in them

I have a DataBase with around +100 tables, like half of tables have column A & column B.
My question is, Can I query all tables that have this columns with a specific values e.g.
SELECT * FROM DATABASE
WHERE
EACHTABLE HAS COLUMN A = 21 //only if table has columns and then values
AND
COLUMN B = 13
I am not sure how exact I will do it, nothing is coming up on google either
You can use the undocumented MS stored procedure sp_MSforeachtable, if you fancy living life recklessly:
create table T1 (
ColumnA int not null,
ColumnB int not null
)
go
create table T2 (
ColumnA int not null,
Column2 int not null
)
go
create table T3 (
Column1 int not null,
ColumnB int not null
)
go
create table T4 (
ColumnA int not null,
ColumnB int not null
)
go
insert into T1 values (1,2);
insert into T2 values (3,4);
insert into T3 values (5,6);
insert into T4 values (7,8);
go
create table #Results (TableName sysname,ColumnA int,ColumnB int)
exec sp_MSforeachtable 'insert into #Results select ''?'',ColumnA,ColumnB from ?',
#whereand = ' and syso.object_id in (select object_id from sys.columns where name=''ColumnA'') and syso.object_id in (select object_id from sys.columns where name=''ColumnB'')'
select * from #Results
drop table #Results
Result:
TableName ColumnA ColumnB
------------------------------------- ----------- -----------
[dbo].[T1] 1 2
[dbo].[T4] 7 8
By default, sp_MSforeachtable will, as its name implies, perform the same task for each table in the database. However, one optional parameter to this procedure, called #Whereand, can be used to modify the WHERE clause of the internal query that enumerates the tables in the database. It helps to know that this internal query has already established two aliases to some of the system views. o is an alias for sysobjects (the legacy system view). syso is an alias for sys.all_objects (a more modern system view).
Once sp_MSforeachtable has decided which tables to run against, it will execute the query given to it as its first parameter. But, it will replace ? with the schema and table name (? is the default replacement character. This can be changed as needed)
In this case, I chose to create a temp table, then have each selected table store its results into this temp table, and after sp_MSforeachtable has finished running, to select the combined results out with no further processing.
There is a similar (and similarly undocumented) procedure called sp_MSforeachdb which will access each user database on the server. These can even be combined (although you have to be careful with doubling up ' quote characters twice, at times). However, there's no equivalent sp_MSforeachcolumn.
Try this:
select t.name from sys.objects t inner join sys.columns c
on t.name=OBJECT_NAME(c.object_id)
where t.type='U'
and c.name in('col1','col2')
group by t.name
having COUNT(*) = 2
order by 1
Then you just loop through all the tables and fine the values for these columns.
Like
Declare #out TABLE(tblname varchar(100))
if exists(select * from tbl1 where col1='21' and col2='22')
BEGIN
INSERT INTO #out
select tbl1
END
You can try like this using dynamic query.
select 'select * from '+table_name+ ' where'+column_name+'=21'
from information_schema.columns where column_name = 'A'
I suggest to use two steps:
First, find out all tables in your database that have these two columns and use it for a temporal derived table. For I am not an expert in SQL-Server 2008 I recommend to have a look at the whitepages.
The expression might look like this:
SELECT tablename
FROM information_schema.tables sdbt
WHERE "column a" IN
(SELECT columns
FROM information_schema.columns col
WHERE col.tablename = sdbt.tablename)
Second, use a expresssion to filter the results according to your demanded values.
This command should do the trick in one go, only for column A, amend accordingly to include any other columns you need:
exec sp_MSforeachtable
#command1=N'SELECT * FROM ? WHERE A = 21',
#whereand=' and o.name IN (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = ''A'') '

Using variables in stored procedures

I am using Microsoft SQL server and writing a stored procedure that contains many select statements. Here I want two variables that hold results of two select statements, and I want to add those two variables to get final result. Please help me doing this (syntax and example).
Below is the syntax for SQL Server:
DECLARE #UserEmail Varchar(250)
DECLARE #LoginID INT
SET #UserEmail = 'a#b.org'
select #LoginID = LoginID from Login L
Where L.UserEmail = #UserEmail
You should clarify which DB you are using. In MS SQL Server, you can use temporary table variable like this:
BEGIN
SELECT product_id,product_name INTO #temp1 FROM products;
SELECT product_id,product_name INTO #temp2 FROM products;
SELECT * FROM #temp1
UNION
SELECT * FROM #temp2;
END
There are several types of temporary table variable in MS SQL Server.I've used one of them.To know more about this, just search "MS SQL Server Temporary tables" in web.
EDIT:
Here is another example with another type of temporary table variable in MS SQL Server.
DECLARE #temp1 TABLE (product_id INT,product_name VARCHAR(100));
DECLARE #temp2 TABLE (product_id INT,product_name VARCHAR(100));
INSERT INTO #temp1 SELECT product_id,product_name FROM products WHERE cat_id=1;
INSERT INTO #temp2 SELECT product_id,product_name FROM products WHERE cat_id=2;
SELECT product_id,product_name
FROM #temp1
UNION
SELECT product_id,product_name
FROM #temp2;

SQL Select Statement including SP Call has syntax error

MYTABLE has ID column. However, following query generates syntax error.
SELECT ID FROM MYTABLE
WHERE ID = EXEC MY_SP ID
What do you think is wrong here?
You can't call stored procedures inline like this.
A couple of options include:
1) Execute the stored procedure and store the results in a temp table. Then use that temp table.
e.g.
CREATE TABLE #Example
(
ID INTEGER
)
INSERT #Example
EXECUTE My_SP
SELECT t.ID FROM MyTable t JOIN #Example e ON t.ID = e.ID
DROP TABLE #Example
2) convert the sproc to a user defined function which you CAN call inline
e.g.
CREATE FUNCTION dbo.MyFunc()
RETURNS TABLE
AS
RETURN
(
SELECT ID FROM SomeTable WHERE ....
)
SELECT t.ID FROM MyTable t JOIN dbo.MyFunc() f ON t.ID = f.ID
3) If the sproc returns a single ID, consider returning an OUTPUT parameter from the sproc instead and use like this:
DECLARE #ID INTEGER
EXECUTE MY_SP #ID OUTPUT
SELECT ID FROM MYTABLE
WHERE ID = #ID
I don't think you need the exec statement, just call the sp, exec is expected to be a separate statement
I don't think you can do that at all. Are you perhaps thinking of a User Defined Function rather than a stored Procedure. Based on the context, you'll need a scalar UDF.
Try this:
SELECT ID FROM MYTABLE WHERE ID = ##SPID