Check stored procedure return value - sql

A stored procedure is returning values like :
Text Value
sdsd 555
dsaa 544
swewe 745
And if it fails, it's returning like :
Standard
No Records Fouond
How can I distinguish among this 2 results in SQL query level?
Note : I can not modify the stored procedure

use the output of proc to find out that.
IF EXISTS(
SELECT name
FROM sysobjects
WHERE name = N'Pr_Test'
AND type = 'P' )
DROP PROCEDURE Pr_Test
GO
Create Procedure Pr_Test
(
#output BIT=0
)
As
BEGIN
SET NOCOUNT ON
IF #output = 0
SELECT 'No Records Fouond' AS [STANDARD]
ELSE
SELECT 'abc' AS [text], 1 AS [VALUE]
SET NOCOUNT OFF
END
Go
SET NOCOUNT ON
DECLARE #ProcOutput TABLE
(
column1 sysname NOT NULL
)
INSERT INTO #ProcOutput(Column1)
EXEC Pr_Test
IF EXISTS (SELECT TOP 1 1 FROM #ProcOutput WHERE column1='No Records Fouond')
PRINT ' this is failed select from proc'
ELSE
PRINT 'proc has some results'
SET NOCOUNT OFF

Related

There is already an object named '#BaseData' in the database

Below is a snippet of my code.
I am wanting to filter my data based upon a variable.
When I try to run the code, it returns an error of "There is already an object named '#BaseData' in the database.". I am not sure as to why this is the case; I have put extra checks within the IF statements to drop the temp table if it already exists but to no avail.
Are you able to help or provide an alternative solution please?
DECLARE #Variable AS VARCHAR(20) = 'Example1'
IF OBJECT_ID(N'TEMPDB..#BaseData') IS NOT NULL
DROP TABLE #BaseData
IF #Variable = 'Example1'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
END
IF #Variable = 'Example2'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
WHERE
[column] = 1
END
IF #Variable = 'Example3'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
WHERE
[column] = 0
END
While code is compiled by SQL, creation of same #table is found in each condition so it doesn't work.
One possible solution would be to create table and than insert data conditionally.
-- DROP TEMP TABLE IF EXISTS
IF OBJECT_ID(N'TEMPDB..#BaseData') IS NOT NULL
DROP TABLE #BaseData
GO
-- CRATE TEMP TABLE WITH TempId, AND SAME STRUCTURE AS YOUR TABLE
SELECT TOP 0 CONVERT(INT, 0)TempId, * INTO #BaseData FROM TestTable
-- DECLARE VARIABLE
DECLARE #Variable AS VARCHAR(20)= 'Example1'
-- INSERT DATA IN TABLE DEPENDING FROM CONDITION
IF (#Variable = 'Example1')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable
END
IF (#Variable = 'Example2')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable WHERE Id = 1
END
IF (#Variable = 'Example3')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable WHERE Id = 2
END

Stored procedure returning result even thought it's not supposed to

I have a stored procedure which looks like following:
ALTER PROCDURE [dbo].[zsp_selectallupceans_listProduction]
(#UPCList NVARCHAR(4000),
#EANList NVARCHAR(4000),
#Type TINYINT)
AS
SELECT
dd.UPC, dd.EAN, dd.EBAYID AS ItemID
FROM
ThirdPartyData AS dd
WHERE
EXISTS (SELECT 1 FROM dbo.SplitStringProduction(#UPCList,',') S1
WHERE dd.UPC = S1.val)
OR EXISTS (SELECT 1 FROM dbo.SplitStringProduction(#EANList,',') S2
WHERE dd.EAN = S2.val)
AND dd.Type = #Type
The parameters are passed like following:
#UPCList='709127309019',
#EanList='0709127309019',
#Type=4
The "SplitStringProduction" function looks like this:
ALTER FUNCTION [dbo].[SplitStringProduction]
(#string NVARCHAR(MAX),
#delimiter NVARCHAR(5))
RETURNS #t TABLE
(
val NVARCHAR(500)
)
AS
BEGIN
DECLARE #xml XML
SET #xml = N'<root><r>' + replace(#string,#delimiter,'</r><r>') + '</r></root>'
INSERT INTO #t(val)
SELECT
r.value('.','varchar(500)') AS item
FROM
#xml.nodes('//root/r') as records(r)
RETURN
END
Now when I do a simple select from my table like following:
select *
from thirdpartydata dd
where dd.UPC = '709127309019' -- note this is one of the parameters passed to the stored procedure...
I will get only 1 result with a column Type set to "1"....
Now when I try out my stored procedure:
exec zsp_selectallupceans_listProduction '709127309019','0709127309019',4
I still get 1 result, even though I'm not supposed to get any result, because if you can see the "Type" parameter is set to 4, thus no matching records should be found....
What am I doing wrong here, I can't seem to figure it out ??
You need to enclose the OR condition inside parenthesis:
WHERE (
EXISTS (SELECT 1 FROM dbo.SplitStringProduction(#UPCList,',') S1 WHERE dd.UPC=S1.val)
OR EXISTS (SELECT 1 FROM dbo.SplitStringProduction(#EANList,',') S2 WHERE dd.EAN=S2.val)
) AND dd.Type = #Type
Without them your query like this:
WHERE EXISTS (...)
OR (EXISTS (...) AND dd.Type = #Type)
And the result your get is because the first OR condition matches.

How to pass name of temp table created in main sp to inner sp in sql?

These are sample tables
UserDetails : id,UserName,IsShow
Brand : id,BrandName
Product : id,ProductName
BrandProduct:id,brandid,productid,price
If Isshow is false, show entire price else hide second -fourth digit.(Price is 5 digits)
create procedure Sp_Details
#brandid int,
#productid int,
#IsShow bit
as
begin
select SomeColumns
into #tableForMechanism
from SomeData
if #IsShow = 0 then
begin
select SomeColumns from #tableForMechanism
end
else
begin
-- Here want to pass table name created by this sp now
-- So can check that table is exist.
-- Because Inner sp is generic.From next 20 sp,have to call
-- same sp.That's why can't give same temp table name because
-- their structure may be different
exec innerDetailsProcedure
end
end
go
create procedure innerDetailsProcedure
#tablename varchar(2000)
as
begin
if OBJECT_ID(#tablename) is NULL
begin
raiserror('Table for mechanism is not created', 16, 1)
return -1
end
else
begin
--update that table
update #tablename
set price = REPLACE(Price, (SUBSTRING(Price,2, 3*#Isshow)), 'xxx')
end
end
What is size of name of temp table created?How to fetch temp table created by this sp now for this session?
So you want to inside a proc check if a #temp table exists, based on a table name that you have in a parameter to that proc? If so, see below. You have to prefix with the database name tempdb in your check with OBJECT_ID():
CREATE PROC p #t1 sysname ,#t2 sysname AS IF OBJECT_ID('tempdb..' + #t1) IS NOT NULL PRINT '#t1 exists'
IF OBJECT_ID('tempdb..' + #t2) IS NOT NULL PRINT '#t2 exists' GO
CREATE TABLE #t(c1 int)
EXEC p #t1 = '#t', #t2 = '#doesntexist'

T-SQL If Else condition on the same Temp Table

Here is what I am trying to do:
IF len(Variable) > 1
BEGIN
SELECT * INTO #TEMPTAB FROM multiple joins
END
ELSE
BEGIN
SELECT * INTO #TEMPTAB FROM different multiple joins
END
SELECT * FROM #TEMPTAB more large number of multiple joins & where & groupby
ERROR: There is already an object #TEMPTAB defined
-- Because of select * into in IF and ELSE both
I don't want to create a temp table prior cause it has a lot of columns to be defined.
Is there a way around it?
This was a fun problem for me that is... Well I figured out four ways to do it. One is with a view, one with a temp Table, one with a physical table, and one with a stored procedure and global temp table. Let me know if you have any questions.
View
DECLARE #Variable VARCHAR(10) = 'aa';
IF LEN(#Variable) > 1
BEGIN
EXEC('CREATE VIEW yourView AS SELECT ''Greater than 1'' col')
END
ELSE
BEGIN
EXEC('CREATE VIEW yourView AS SELECT ''Less than 1'' col')
END
SELECT *
FROM yourView;
DROP VIEW yourView;
Temp Table
DECLARE #Variable VARCHAR(100) = 'aa',
--Default value is 0
#percent INT = 0;
--If the length > 1, then change percent to 100 as to return the whole table
IF LEN(#Variable) > 1
SET #percent = 100;
--If the length <=1, then #percent stays 0 and you return 0 percent of the table
SELECT TOP(#percent) PERCENT 'Greater than 1' col INTO #TEMPTAB
--If you didn't populate the table with rows, then use this query to populate it
IF(#percent = 0)
BEGIN
INSERT INTO #TEMPTAB
SELECT 'Less than 1' col
END
/*your 1k lines of code here*/
SELECT *
FROM #TEMPTAB
--Cleanup
DROP TABLE #tempTab
Physical Table
DECLARE #Variable VARCHAR(10) = 'A';
IF len(#Variable) > 1
BEGIN
SELECT 'Greater than 1' col INTO TEMPTAB
END
ELSE
BEGIN
SELECT 'Less than 1' col INTO TEMPTAB2
END
IF OBJECT_ID('TEMPTAB2') IS NOT NULL
--SP_Rename doesn't work on temp tables so that's why it's an actual table
EXEC SP_RENAME 'TEMPTAB2','TEMPTAB','Object'
SELECT *
FROM TEMPTAB
DROP TABLE TEMPTAB;
Stored Procedure with Global Temp Table
IF OBJECT_ID('yourProcedure') IS NOT NULL
DROP PROCEDURE yourProcedure;
GO
CREATE PROCEDURE yourProcedure
AS
IF OBJECT_ID('tempdb..##TEMPTAB') IS NOT NULL
DROP TABLE ##tempTab;
SELECT 'Greater than 1' col INTO ##TEMPTAB
GO
DECLARE #Variable VARCHAR(10) = 'aaa';
IF LEN(#Variable) > 1
BEGIN
EXEC yourProcedure;
END
ELSE
BEGIN
SELECT 'Less than 1' col INTO ##TEMPTAB
END
SELECT *
FROM ##TEMPTAB
IF OBJECT_ID('tempdb..##TEMPTAB') IS NOT NULL
DROP TABLE ##TEMPTab;
Didn't you consider dynamic query with global temporary tables? This works for me:
DECLARE #sql NVARCHAR(MAX) = CASE WHEN 1 = 2
THEN 'SELECT * INTO ##TEMPTAB FROM dbo.SomeTable1'
ELSE 'SELECT * INTO ##TEMPTAB FROM dbo.SomeTable2'
END
EXEC (#sql)
SELECT * FROM ##TEMPTAB
DROP TABLE ##TEMPTAB
The first time you ran this code it created the table #TEMPTAB. The next time you ran SQL Server is telling you the table already exists. You should precede your code with the following:
if object_ID('tempdb..#TEMPTAB','U') is not null
drop table #TEMPTAB
This will drop (delete the table if it already exists) and the code that follows will always be able to recreate(or create) the table.

SQL server stored procedure return a table

I have a stored procedure that takes in two parameters. I can execute it successfully in Server Management Studio. It shows me the results which are as I expect. However it also returns a Return Value.
It has added this line,
SELECT 'Return Value' = #return_value
I would like the stored procedure to return the table it shows me in the results not the return value as I am calling this stored procedure from MATLAB and all it returns is true or false.
Do I need to specify in my stored procedure what it should return? If so how do I specify a table of 4 columns (varchar(10), float, float, float)?
A procedure can't return a table as such. However you can select from a table in a procedure and direct it into a table (or table variable) like this:
create procedure p_x
as
begin
declare #t table(col1 varchar(10), col2 float, col3 float, col4 float)
insert #t values('a', 1,1,1)
insert #t values('b', 2,2,2)
select * from #t
end
go
declare #t table(col1 varchar(10), col2 float, col3 float, col4 float)
insert #t
exec p_x
select * from #t
I do this frequently using Table Types to ensure more consistency and simplify code. You can't technically return "a table", but you can return a result set and using INSERT INTO .. EXEC ... syntax, you can clearly call a PROC and store the results into a table type. In the following example I'm actually passing a table into a PROC along with another param I need to add logic, then I'm effectively "returning a table" and can then work with that as a table variable.
/****** Check if my table type and/or proc exists and drop them ******/
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'returnTableTypeData')
DROP PROCEDURE returnTableTypeData
GO
IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'myTableType')
DROP TYPE myTableType
GO
/****** Create the type that I'll pass into the proc and return from it ******/
CREATE TYPE [dbo].[myTableType] AS TABLE(
[someInt] [int] NULL,
[somenVarChar] [nvarchar](100) NULL
)
GO
CREATE PROC returnTableTypeData
#someInputInt INT,
#myInputTable myTableType READONLY --Must be readonly because
AS
BEGIN
--Return the subset of data consistent with the type
SELECT
*
FROM
#myInputTable
WHERE
someInt < #someInputInt
END
GO
DECLARE #myInputTableOrig myTableType
DECLARE #myUpdatedTable myTableType
INSERT INTO #myInputTableOrig ( someInt,somenVarChar )
VALUES ( 0, N'Value 0' ), ( 1, N'Value 1' ), ( 2, N'Value 2' )
INSERT INTO #myUpdatedTable EXEC returnTableTypeData #someInputInt=1, #myInputTable=#myInputTableOrig
SELECT * FROM #myUpdatedTable
DROP PROCEDURE returnTableTypeData
GO
DROP TYPE myTableType
GO
Consider creating a function which can return a table and be used in a query.
https://msdn.microsoft.com/en-us/library/ms186755.aspx
The main difference between a function and a procedure is that a function makes no changes to any table. It only returns a value.
In this example I'm creating a query to give me the counts of all the columns in a given table which aren't null or empty.
There are probably many ways to clean this up. But it illustrates a function well.
USE Northwind
CREATE FUNCTION usp_listFields(#schema VARCHAR(50), #table VARCHAR(50))
RETURNS #query TABLE (
FieldName VARCHAR(255)
)
BEGIN
INSERT #query
SELECT
'SELECT ''' + #table+'~'+RTRIM(COLUMN_NAME)+'~''+CONVERT(VARCHAR, COUNT(*)) '+
'FROM '+#schema+'.'+#table+' '+
' WHERE isnull("'+RTRIM(COLUMN_NAME)+'",'''')<>'''' UNION'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #table and TABLE_SCHEMA = #schema
RETURN
END
Then executing the function with
SELECT * FROM usp_listFields('Employees')
produces a number of rows like:
SELECT 'Employees~EmployeeID~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees WHERE isnull("EmployeeID",'')<>'' UNION
SELECT 'Employees~LastName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees WHERE isnull("LastName",'')<>'' UNION
SELECT 'Employees~FirstName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees WHERE isnull("FirstName",'')<>'' UNION
You can use an out parameter instead of the return value if you want both a result set and a return value
CREATE PROCEDURE proc_name
#param int out
AS
BEGIN
SET #param = value
SELECT ... FROM [Table] WHERE Condition
END
GO
I had a similar situation and solved by using a temp table inside the procedure, with the same fields being returned by the original Stored Procedure:
CREATE PROCEDURE mynewstoredprocedure
AS
BEGIN
INSERT INTO temptable (field1, field2)
EXEC mystoredprocedure #param1, #param2
select field1, field2 from temptable
-- (mystoredprocedure returns field1, field2)
END
The Status Value being returned by a Stored Procedure can only be an INT datatype. You cannot return other datatypes in the RETURN statement.
From Lesson 2: Designing Stored Procedures:
Every stored procedure can return an integer value known as the
execution status value or return code.
If you still want a table returned from the SP, you'll either have to work the record set returned from a SELECT within the SP or tie into an OUTPUT variable that passes an XML datatype.
HTH,
John
Though this question is very old but as a new in Software Development I can't stop my self to share what I have learnt :D
Creation of Stored Procedure:
CREATE PROC usp_ValidateUSer
(
#UserName nVARCHAR(50),
#Password nVARCHAR(50)
)
AS
BEGIN
IF EXISTS(SELECT '#' FROM Users WHERE Username=#UserName AND Password=#Password)
BEGIN
SELECT u.UserId, u.Username, r.UserRole
FROM Users u
INNER JOIN UserRoles r
ON u.UserRoleId=r.UserRoleId
END
END
Execution of Stored Procedure:
(If you want to test the execution of Stored Procedure in SQL)
EXEC usp_ValidateUSer #UserName='admin', #Password='admin'
The Output:
create procedure PSaleCForms
as
begin
declare
#b varchar(9),
#c nvarchar(500),
#q nvarchar(max)
declare #T table(FY nvarchar(9),Qtr int,title nvarchar (max),invoicenumber nvarchar(max),invoicedate datetime,sp decimal 18,2),grandtotal decimal(18,2))
declare #data cursor
set #data= Cursor
forward_only static
for
select x.DBTitle,y.CurrentFinancialYear from [Accounts Manager].dbo.DBManager x inner join [Accounts Manager].dbo.Accounts y on y.DBID=x.DBID where x.cfy=1
open #data
fetch next from #data
into #c,#b
while ##FETCH_STATUS=0
begin
set #q=N'Select '''+#b+''' [fy], case cast(month(i.invoicedate)/3.1 as int) when 0 then 4 else cast(month(i.invoicedate)/3.1 as int) end [Qtr], l.title,i.invoicenumber,i.invoicedate,i.sp,i.grandtotal from ['+#c+'].dbo.invoicemain i inner join ['+#c+'].dbo.ledgermain l on l.ledgerid=i.ledgerid where (sp=0 or stocktype=''x'') and invoicetype=''DS'''
insert into #T exec [master].dbo.sp_executesql #q
fetch next from #data
into #c,#b
end
close #data
deallocate #data
select * from #T
return
end
Here's an example of a SP that both returns a table and a return value. I don't know if you need the return the "Return Value" and I have no idea about MATLAB and what it requires.
CREATE PROCEDURE test
AS
BEGIN
SELECT * FROM sys.databases
RETURN 27
END
--Use this to test
DECLARE #returnval int
EXEC #returnval = test
SELECT #returnval