How to reference the column value in same stored procedure - sql-server

I already have some stored procedure, and now I want to make it one stored procedure.
My stored procedure code looks like this:
ALTER PROCEDURE [dbo].[UP_SELECT_TargetSiteStatus_For_ExcelExport]
#AppUrl nvarchar(200)
AS
BEGIN
SET NOCOUNT ON;
-- Web Application
SELECT
AppName, AppUrl, AppPort,
AppDefaultTimeZone, AppMaxiumFileSize,
AppContentDatabaseCount, AppSitesCount
FROM
tb_SPStatusWebApplications
WHERE
AppUrl = #AppUrl
-- Content Database
SELECT
ContentDBAppName, ContentDBID, ContentDBName,
ContentDBServerName, ContentDBStatus,
ContentDBSize, ContentDBSiteCount
FROM
tb_SPStatusContentDatabases CD
INNER JOIN
tb_SPStatusWebApplications WA ON CD.ContentDBAppName = WA.AppName
WHERE
CD.ContentDBAppName = ? <-- Change this...
END
In first Select query, AppName value is like this "Site1".
And I want to use AppName value to compare with ContentDBAppname in second SELECT query where clause
WHERE
CD.ContentDBAppName = [how to get AppNames value]
But I`m not sure how can I make it...
Please somebody help me

TRY THIS: your second select statement will be as below and you are already joining AppName in the join so you can add in AND condition as
AND WA.AppUrl = #AppUrl or in where.
SELECT
ContentDBAppName
, ContentDBID
, ContentDBName
, ContentDBServerName
, ContentDBStatus
, ContentDBSize
, ContentDBSiteCount
FROM tb_SPStatusContentDatabases CD
INNER JOIN tb_SPStatusWebApplications WA ON CD.ContentDBAppName = WA.AppName
AND WA.AppUrl = #AppUrl
It will return AppName exactly same as first select statement and will perform same in the join as per your expectation.

Related

Stored procedure with conditional Where clause in SQL Server

I am creating a SQL Server stored procedure. It's a simple SELECT query that I am building. One of the parameters is to look for a flag parameter. If that parameter is left blank, then the SELECT should default to NOT having the WHERE clause at all.
CREATE PROCEDURE sprocA
#flagInd int
AS
BEGIN
SELECT intID, strQuestion, strAnswer, intCategory, intOrder
FROM tblA
-- Right here is where I am looking for the logic of the #flagInd to be evaluated.....
-- if #flagInd = 1 then 'WHERE flgInd=1'
-- else if #flagInd=0 then 'WHERE flgInd=0'
-- else if #flagInd IS NULL then ''
It's just a simple query and a simple thought I had, not sure if it can be done without nesting and rewriting the whole SELECT statement as part of of the IF statement.
This can be done like:
SELECT intID, strQuestion, strAnswer, intCategory, intOrder
FROM tblA
WHERE flgInd = #flgInd OR #flgInd IS NULL;
You can also use a CASE expression:
SELECT intID, strQuestion, strAnswer, intCategory, intOrder
FROM tblA
WHERE CASE
WHEN flgInd = #flgInd THEN 1
WHEN #flgInd IS NULL THEN 1
ELSE 0
END = 1;
There appears to just be a one to one mapping (from the parameter to the column) so why not use a simple where clause?
CREATE PROCEDURE sprocA
#flagInd int
AS
BEGIN
SELECT intID, strQuestion, strAnswer, intCategory, intOrder
FROM tblA WHERE flgInd = #flagInd;

Convert SQL Server stored procedure to Oracle procedure to query from tables

I'm trying to move from SQL Server to an Oracle database. I have to move my stored procedure from SQL Server to Oracle that do a query from multiple table with an INNER JOIN. I am trying to clarify few things here.
SQL Server stored procedure:
[dbo].[QueryAll]
#score1_min int = 0,
#score1_max int = 999,
#type1 varchar (1) = '%',
AS
BEGIN
SET NOCOUNT ON;
SELECT *
FROM FUNIJ1 uni
INNER JOIN CAPI99 api99 on api99.application_id = uni.application_id
INNER JOIN CAPI41 api41 on api41.application_id = uni.application_id
INNER JOIN CAPI10 api10 on api10.application_id = uni.application_id
WHERE
api10.score1 BETWEEN #score1_min AND #score1_max
AND uni.type1 LIKE #type1
END
And my Oracle procedure
create or replace PROCEDURE QUERYALL
(
SCORE1_MIN IN NUMBER DEFAULT 0
, SCORE1_MAX IN NUMBER DEFAULT 999
, TYPE IN VARCHAR2
)
AS
BEGIN
SELECT *
FROM FUNIJ1 uni
INNER JOIN CAPI99 on CAPI99.APPLICATION_ID = uni.APPLICATION_ID
INNER JOIN CAPI41 on CAPI41.APPLICATION_ID = uni.APPLICATION_ID
INNER JOIN CAPI10 on CAPI10.APPLICATION_ID = uni.APPLICATION_ID
WHERE
CAPI10.score1 BETWEEN score1_min AND score1_max
AND uni.type LIKE type
END REPOQUERYALL ;
I used % as default query parameter to return all values in SQL Server
in case of no input from user. I am not sure what I have to use in Oracle as default value to return all.
List item Oracle is using new term INTO following to SELECT *. I am not sure whether I need to use INTO or cursor in this case. I don't know WHICH will be appropriate here and HOW to use it.
I'd appreciate if anybody can transfer this SQL Server to an Oracle procedure. I am not sure that my Oracle is 100% correct.
Here is what you need to understand about Oracle stored procedure - unlike in SQL Server, you can't just do SELECT ... in any programming block, unless this is subselect or select... into....
If the goal is to return record set from procedure, in Oracle, you have to add a Sys_RefCursor output parameter and open this ref cursor with your select statement.
You're not far away - check this example .And remember, when you do Open <cursor_name> FOR ..., what comes after FOR can be dynamic SQL string or just compiled SQL.
Here is the code that worked for me with Sys_Cursor. Thanks #TS for the help that guide me to this answer.
create or replace PROCEDURE QUERYALL
(
o_Cursor OUT SYS_REFCURSOR
)
AS
BEGIN
O_Cursor := NULL;
OPEN O_Cursor FOR
SELECT * FROM FUNIJ1
INNER JOIN CAPI99 on CAPI99.APPLICATION_ID = FUNIJ1 .APPLICATION_ID
INNER JOIN CAPI41 on CAPI41.APPLICATION_ID = FUNIJ1 .APPLICATION_ID
INNER JOIN CAPI10 on CAPI10.APPLICATION_ID = FUNIJ1 .APPLICATION_ID
WHERE
----
----
END QUERYALL;
When you use this procedure in Java to display the table, you need to call Sys_Cursor into Resultset.
String sp= "{CALL QUERYALL(?)}"; // Procedure calling with Sys_Cursor
cst = con.prepareCall(sql);
cst.registerOutParameter(1, OracleTypes.CURSOR);
cst.executeUpdate();
rs = (ResultSet) cst.getObject(1);
while(rs.next()) {
----
----
}

Output sql query to a variable then create a new query

I'm trying to output the query results from one table and using that same variable as a 'like' in another table.
The first part of the query is supposed to get me everything *. The variable (or array) will be used in the second part of the query as part of 'like'.
This is what I have:
DECLARE #UpnPref nvarchar(100), #WC nvarchar(10)
Set #UpnPref = 0
Set #WC = '*'
Select #upnpref = UpnPrefix from dbo.ADUsers where UPNPrefix = #WC
print #upnpref <-- returns a 0
Select * from dbo.UserMailbox where LinkedAccount like '%' + #UpnPref +'%'
If what you're trying to do is select everything from dbo.UserMailbox that has LinkedAccount matching UpnPrefix of every record in dbo.ADUsers, you can do it so:
SELECT U.*
FROM dbo.UserMailbox U
INNER JOIN dbo.ADUsers A ON U.LinkedAccount = A.UpnPrefix

stored procedure always returning one row result in sql server

I have a table like this in my sql server:
TransactID Dtid Sid
1086 5 4
1086 7 8
1086 4 3
i want to take corresponding name of Dtid and Sid from resepective table.so i created stored procedure like this:
ALTER procedure [dbo].[PDTDamageFetch]
#Carid NVARCHAR(50)
AS
BEGIN
SET NOCOUNT ON
declare #transid integer,#dtid integer,#sid integer,#Damage nvarchar(100),#side nvarchar(100)
select #transid= t.transactID from Transaction_tbl t where t.TBarcode=#Carid
select #dtid= tr.Dtid from TransactDamageAssign_tbl tr where tr.transactID=#transid
select #sid= tr.sid from TransactDamageAssign_tbl tr where tr.transactID=#transid
select #Damage=dt.DtName from DamageType_tbl dt where dt.Dtid=#dtid
select #side= ds.SName from DamageSide_tbl ds where ds.Sid=#sid
select #Damage,#side
end
then i executed my stored procedure passing corresponding carid..transactID of particular car id is 1086 but stored procedure always showing one row of data..how i can replicate my issue..my
expected out put at this stage is:
Damage Side
scrtch front
broken Back
damged side
Try this query instead of yours. You are just assining one value to a variable, and that's why you just get one row
SELECT * FROM Transaction_tbl t
INNER JOIN TransactDamageAssign_tbl tr ON tr.transactID = t.transactID
INNER JOIN DamageType_tbl dt ON dt.Dtid = tr.Dtid
INNER JOIN DamageSide_tbl ds ON ds.Sid = tr.sid
WHERE t.TBarcode=#Carid
I think you should try table variables or temp tables to list all records.
The way you are trying, will always return the very last row of matching condition.

Invalid column in stored procedure

I have a query in a stored procedure, it works fine. now I want to add a column the it show error.
My stored procedure code is:
ALTER PROCEDURE dbo.test
#SDate DATETIME =Null
, #EDate DATETIME=Null
,#period int=Null
AS BEGIN
SET NOCOUNT ON;
if #period = 1
Begin
SELECT
t.TotalQuote
, t.QuoteAmount
,t.avgProbQ
, t2.TotalOrders
, t2.OrderAmount
,t3.totalSales
,t3.Prob
FROM (SELECT a = 1) a
CROSS JOIN (
SELECT
TotalQuote = COUNT(quoteid)
, QuoteAmount = SUM(totalamount)
,avgProbQ=SUM(CloseProbability)/COUNT(CloseProbability)
FROM dbo.QuoteBase join dbo.OpportunityBase on dbo.QuoteBase.opportunityid=dbo.OpportunityBase.opportunityid
WHERE
Month(dbo.QuoteBase.CreatedOn)=Month(getdate()) And YEAR(dbo.QuoteBase.CreatedOn)=YEAR(GETDATE())
) t
CROSS JOIN (
SELECT
TotalOrders = COUNT(salesorderid)
, OrderAmount = SUM(totalamount)
FROM dbo.SalesOrderBase join dbo.OpportunityBase on dbo.SalesOrderBase.Opportunityid=dbo.OpportunityBase.Opportunityid
Where Month(dbo.SalesOrderBase.CreatedOn)=Month(getdate()) And YEAR(dbo.SalesOrderBase.CreatedOn)=YEAR(GETDATE())
) t2
CROSS Join(
SELECT
TotalSales=COUNT(dbo.OpportunityBase.opportunityid)
,Prob=SUM(CloseProbability)/COUNT(CloseProbability)
FROM dbo.OpportunityBase join dbo.SalesorderBase on dbo.SalesOrderBase.Opportunityid=dbo.OpportunityBase.Opportunityid
WHERE Month(dbo.OpportunityBase.CreatedOn)=Month(getdate()) And YEAR(dbo.OpportunityBase.CreatedOn)=YEAR(GETDATE())
And dbo.SalesorderBase.StateCode=4
)t3
END
It works fine but when I add a new column like t.test, then it shows error
Msg 207, Level 16, State 1, Procedure test, Line 23
Invalid column name 'test'.
If anyone has an idea please share with me
I am not sure what is your table looked like
it seems you are adding test to your stored procedure but its not added in your database table
This is what I can say by looking the error message. Hope it helps
Not sure what you are trying to do, but guessing, if you are trying to add a column to the output of stored procedure, that is not in the table that the stored procedure is reading data from, then you have to put a literal expression into the select clause, with a defined column name like below: This example uses a string literal, but it can be any datatype...
SELECT 'A String literal to be added to output' As NewColumnName,
t.TotalQuote
, t.QuoteAmount
,t.avgProbQ
, t2.TotalOrders
, t2.OrderAmount
,t3.totalSales
,t3.Prob
etc....
You're getting this error because the column test does not exist in this query:
CROSS JOIN (
SELECT
TotalQuote = COUNT(quoteid)
, QuoteAmount = SUM(totalamount)
,avgProbQ=SUM(CloseProbability)/COUNT(CloseProbability)
FROM dbo.QuoteBase join dbo.OpportunityBase on dbo.QuoteBase.opportunityid=dbo.OpportunityBase.opportunityid
WHERE
Month(dbo.QuoteBase.CreatedOn)=Month(getdate()) And YEAR(dbo.QuoteBase.CreatedOn)=YEAR(GETDATE())
) t
but, if you were to add to that query a column named test then it would succeed. It could be a string literal like 'Some literal value' AS test if necessary.

Resources