Using variables in stored procedures - sql

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;

Related

different results of IN Condition

Don't quite understand IN statement. First variant works fine:
select manufacturers.id
from manufacturers
where manufacturers.id in (select manufacturerId
from pcs group by manufacturerId
having count(manufacturerId) > 1)
But when I make subquery a procedure:
CREATE PROCEDURE [dbo].Get_manufacturers #productType varchar(50)
as
begin
declare #query varchar(500)
set #query='select manufacturerId from ' + QuoteName(#productType) + '
group by manufacturerId having count(manufacturerId) > 1'
declare #t table (manufacturerId int)
insert into #t exec(#query)
select manufacturerId from #t;
end
select manufacturers.id
from manufacturers
where manufacturers.id in (Get_manufacturers 'pcs')
I get an error: Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'pcs'
Get_manufacturers 'pcs' works properly. Where am I wrong?
Don't quite understand IN statement
...
Get_manufacturers 'pcs' works properly - it returns a table
You misunderstand both stored procedures and IN condition.
From IN (Transact-SQL):
test_expression [ NOT ] IN
( subquery | expression [ ,...n ]
)
What the stored procedure returns is not a subquery, neither it's an expression.
Here is a link to understand what subquery is Using a Subquery in a T-SQL Statement
A subquery is a SELECT statement that is nested within another T-SQL
statement
So stored procedure is not a subquery, it's just not a SELECT statement.
But even when you say that stored procedures returns a table it's wrong: you can JOIN a table to another table but you cannot join the result of stored procedure.
And even if you "see" the result set returned by a procedure as a "table" it's not a table.
Based on Rokuto and Gordon Linoff suggestions, Alter the procedure by omitting the table declaration:
ALTER PROCEDURE [dbo].Get_manufacturers #productType nvarchar(50)
as
begin
declare #query nvarchar(500)
set #query= N'select manufacturerId from ' + QuoteName(#productType) + '
group by manufacturerId having count(manufacturerId) > 1'
---declare #t table (manufacturerId int)
---insert into #t exec(#query)
---select manufacturerId from #t;
exec(#query)
end
GO
Then, Use a temporary table to fill in the results of the stored procedure.
IF(OBJECT_ID('tempdb..#tmp_manufacturers') IS NOT NULL)
BEGIN
DROP TABLE #tmp_manufacturers
END
CREATE TABLE #tmp_manufacturers
(
manufacturerId int
)
INSERT INTO #tmp_manufacturers (manufacturerId)
EXEC dbo.Get_manufacturers 'pcs'
lastly, add it to your IN condition.
select m.id
from manufacturers M
where m.id IN (select t.manufacturerId From #tmp_manufacturers T)
As #Gordon Linoff said, procedures does not return tables.
But, if you want to store output data from stored procedures, you need to put it into table e. g.:
DECLARE #manufactures TABLE (Id int)
INSERT INTO #manufactures
exec Get_manufacturers 'pcs'
select manufacturers.id
from manufacturers
where manufacturers.id IN (SELECT Id FROM #manufactures)
Instead of table variable, you can use temporary table.

Combine sp result in select as column

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

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 Azure doesn't support 'select into' - Is there another way?

I have a very complicated table I'd like to take a temporary backup of whilst I make some changes. Normally, I'd just do the following:
SELECT *
INTO temp_User
FROM dbo.[User] AS u
Unfortunately I'm using Azure, and it appears this isn't supported:
Msg 40510, Level 16, State 1, Line 2 Statement 'SELECT INTO' is not
supported in this version of SQL Server.
Is there a way to re-create this feature into a function, potentially? I could do this by scripting the table, creating it and then inserting data using a select statement but given how frequently I use Azure, and how many databases I need to work on in this area this is very unwieldy.
Azure requires a clustered index on all tables, therefore SELECT INTO is not supported.
You'll have to:
CREATE TABLE temp_User () --fill in table structure
INSERT INTO temp_User
SELECT *
FROM dbo.[User]
To script table easily you can write your own or use one of the answers to this question:
Script CREATE Table SQL Server
Update: As Jordan B pointed out, V12 will include support for heaps (no clustered index requirement) which means SELECT INTO will work. At the moment V12 Preview is available, Microsoft of course only recommends upgrading with test databases.
The new Azure DB Update preview has this problem resolved:
The V12 preview enables you to create a table that has no clustered
index. This feature is especially helpful for its support of the T-SQL
SELECT...INTO statement which creates a table from a query result.
http://azure.microsoft.com/en-us/documentation/articles/sql-database-preview-whats-new/
Unfortunately it cant be done. Here is how I worked around it:
Open SQL Server Management Studio
Right click on the table
Select Script as ... Create Table
Edit the generated script to change the table name to what you specified in your query
Execute your query
INSERT INTO temp_User
SELECT * FROM dbo.[User]
You can try the above. It's basically a select that is applied to an insert statement
http://blog.sqlauthority.com/2011/08/10/sql-server-use-insert-into-select-instead-of-cursor/
Lets assume you have a table with Id, Column1 and Column2. Then this could be your solution
CREATE TABLE YourTableName_TMP ....
GO
SET IDENTITY_INSERT YourTableName_TMP ON
GO
INSERT INTO YourTableName_TMP
([Id] ,[Column1] ,[Column2])
SELECT [Id] ,[Column1] ,[Column2]
FROM
(
SELECT *
FROM
(
SELECT [Id] ,[Column1] ,[Column2] ROW_NUMBER() OVER(ORDER BY ID DESC) AS RowNum
FROM YourTableName
)
WHERE RowNum BETWEEN 0 AND 500000
)
GO
SET IDENTITY_INSERT YourTableName_TMP OFF
GO
First you create a temporary table and then you insert rows windowed. It's a mess, I know. My experiences are, that executing this using SQL Server Management Studio from a client makes approximately 200.000 rows a minute.
As wrote above - you need to rewrite your query from using select into to create table like
It is my sample. Was :
select emrID, displayName --select into
into #tTable
from emrs
declare #emrid int
declare #counter int = 1
declare #displayName nvarchar(max)
while exists (select * from #tTable)
begin
-- some business logic
select top 1 #displayName = displayname
from #tTable
group by displayname
update emrs set groupId = #counter where #displayName = displayname
delete #tTable
where #displayName = displayname
set #counter = #counter + 1
end
drop table #tTable
Modified :
CREATE TABLE #tTable ([displayName] nvarchar(max)) --create table
INSERT INTO #tTable -- insert to next select :
select displayName
from emrs
declare #emrid int
declare #counter int = 1
declare #displayName nvarchar(max)
while exists (select * from #tTable)
begin
-- some business logic
select top 1 #displayName = t.displayName
from #tTable as t
group by t.displayname
update emrs set groupId = #counter where #displayName = displayname
delete #tTable
where #displayName = displayname
set #counter = #counter + 1
end
drop table #tTable
Do not forget to drop your temp table.
Also, you can find more simple example with description here :
http://www.dnnsoftware.com/wiki/statement-select-into-is-not-supported-in-this-version-of-sql-server

how can I count the row number in a virtual table that is temporarily created in the stored procedure

I have stored procedure like this
create store procedure onetimeprocessing
as
begin
declare #input_data (id int,title varchar(400),topic varchar(400))
insert into #input_data
select id,title,topic from dB
I just want to count number of records in the virtual table #input_data
How should I get the count.Please help me
Thanks in Advance
select count(*) from #input_data
or after the insert
select ##rowcount
Why not just have this?
create store procedure onetimeprocessing
as
begin
select COUNT(*) as TheCount from dB
Edit
I'm having difficulty understanding why other folk would suggest to load #inputdata first, then count from that. or return an extra result set with ##ROWCOUNT...
Its available in ##ROWCOUNT:
declare #input_data table (id int,title varchar(400),topic varchar(400))
insert into #input_data select ....
SELECT ##ROWCOUNT