When trying to create a task(from a Snowflake worksheet) with two declared variables of type VARCHAR, an error is given for an <EOF> on the line when declaring the first variable. I am unsure of why this happens since in the examples in Snowflakes documentation on task creation the same syntax to create a variable is used.
Here is the query.
create or replace task TEST_STORED_PROC_TASK
warehouse = COMPUTE_XS
schedule = '1 minute'
AS
DECLARE
delete_query VARCHAR;
insert_query VARCHAR;
BEGIN
delete_query := 'DELETE FROM TEST_TASK_TBL_DEST
USING TEST_STORED_PROC_TASK_STREAM
WHERE TEST_TASK_TBL_DEST.DATA_INDEX = TEST_STORED_PROC_TASK_STREAM.DATA_INDEX
AND TEST_STORED_PROC_TASK_STREAM.METADATA$ISUPDATE;';
insert_query := 'INSERT INTO TEST_TASK_TBL_DEST (DATA_INDEX ,COMP_ID ,ACCOUNT_ID ,COMP_VERSION ,NAME ,DESCRIPTION ,OBJECT_DICT ,ACTION_TYPE ,CONNECTOR_TYPE ,OUTPUT_PROFILE , PARAMETER_PROFILE)
WITH DEDUPED_COMP AS (
SELECT DATA_INDEX,COMP_ID,ACCOUNT_ID,COMP_VERSION,NAME, DESCRIPTION, PROPERTIES, ROW_NUMBER() OVER (PARTITION BY COMP_ID ORDER BY COMP_VERSION DESC) AS ROW_NUM
FROM TEST_STORED_PROC_TASK_STREAM
WHERE METADATA$ACTION = \'INSERT\'
QUALIFY 1 = ROW_NUM
),
GROUPED_PROPS AS (
SELECT ANY_VALUE(DATA_INDEX) AS DATA_INDEX, COMP_ID, ANY_VALUE(ACCOUNT_ID) AS ACCOUNT_ID, ANY_VALUE(COMP_VERSION) AS COMP_VERSION,
ANY_VALUE(NAME) AS NAME, ANY_VALUE(DESCRIPTION) AS DESCRIPTION, OBJECT_AGG(DISTINCT XMLGET(PROPS.Value,\'Name\'):"$"::string,
XMLGET(PROPS.Value,\'Value\'):"$"::VARIANT) AS OBJECT_DICT
FROM DEDUPED_COMP,
LATERAL FLATTEN(INPUT=>PROPERTIES, MODE=> \'ARRAY\', OUTER=>TRUE) PROPS
GROUP BY COMP_ID
)
SELECT *, OBJECT_DICT:"action-type"::string AS ACTION_TYPE, OBJECT_DICT:"connector-type"::string AS CONNECTOR_TYPE,
OBJECT_DICT:"output-profile"::string AS OUTPUT_PROFILE, OBJECT_DICT:"parameter-profile"::string AS PARAMETER_PROFILE
FROM GROUPED_PROPS;
';
call RUN_TASK_QUERIES(ARRAY_CONSTRUCT(:delete_query, :insert_query));
END;
Here is the error
SQL compilation error: syntax error line 6 at position 25 unexpected '<EOF>'.
The code is executed without error when using Snowsight.
If the ClassicUI is used then wrapping with EXECUTE IMMEDIATE $$ ... $$ will compile it:
create or replace task TEST_STORED_PROC_TASK
warehouse = COMPUTE_XS
schedule = '1 minute'
AS
EXECUTE IMMEDIATE $$
DECLARE
delete_query VARCHAR;
insert_query VARCHAR;
BEGIN
delete_query := 'DELETE FROM TEST_TASK_TBL_DEST
USING TEST_STORED_PROC_TASK_STREAM
WHERE TEST_TASK_TBL_DEST.DATA_INDEX = TEST_STORED_PROC_TASK_STREAM.DATA_INDEX
AND TEST_STORED_PROC_TASK_STREAM.METADATA$ISUPDATE;';
insert_query := 'INSERT INTO TEST_TASK_TBL_DEST (DATA_INDEX ,COMP_ID ,ACCOUNT_ID ,COMP_VERSION ,NAME ,DESCRIPTION ,OBJECT_DICT ,ACTION_TYPE ,CONNECTOR_TYPE ,OUTPUT_PROFILE , PARAMETER_PROFILE)
WITH DEDUPED_COMP AS (
SELECT DATA_INDEX,COMP_ID,ACCOUNT_ID,COMP_VERSION,NAME, DESCRIPTION, PROPERTIES, ROW_NUMBER() OVER (PARTITION BY COMP_ID ORDER BY COMP_VERSION DESC) AS ROW_NUM
FROM TEST_STORED_PROC_TASK_STREAM
WHERE METADATA$ACTION = \'INSERT\'
QUALIFY 1 = ROW_NUM
),
GROUPED_PROPS AS (
SELECT ANY_VALUE(DATA_INDEX) AS DATA_INDEX, COMP_ID, ANY_VALUE(ACCOUNT_ID) AS ACCOUNT_ID, ANY_VALUE(COMP_VERSION) AS COMP_VERSION,
ANY_VALUE(NAME) AS NAME, ANY_VALUE(DESCRIPTION) AS DESCRIPTION, OBJECT_AGG(DISTINCT XMLGET(PROPS.Value,\'Name\'):"$"::string,
XMLGET(PROPS.Value,\'Value\'):"$"::VARIANT) AS OBJECT_DICT
FROM DEDUPED_COMP,
LATERAL FLATTEN(INPUT=>PROPERTIES, MODE=> \'ARRAY\', OUTER=>TRUE) PROPS
GROUP BY COMP_ID
)
SELECT *, OBJECT_DICT:"action-type"::string AS ACTION_TYPE, OBJECT_DICT:"connector-type"::string AS CONNECTOR_TYPE,
OBJECT_DICT:"output-profile"::string AS OUTPUT_PROFILE, OBJECT_DICT:"parameter-profile"::string AS PARAMETER_PROFILE
FROM GROUPED_PROPS;
';
call RUN_TASK_QUERIES(ARRAY_CONSTRUCT(:delete_query, :insert_query));
END;
$$;
Related
My stored procedure is as follows:
DECLARE #LOCATION_ID VARCHAR(MAX) = 3,
#INVENTORY_ITEM_ID VARCHAR(MAX) = '01-4001' ,
#CALLFROM VARCHAR(MAX) = 'FRAMES' --Requested by VIkram Dated 29jan 2020 For MBT :- 25401,25402
BEGIN
SET NOCOUNT ON;
BEGIN TRY
DECLARE #TABLE_LOCATION_ID TABLE
(
ID INT,
LOCATION_ID INT
)
INSERT INTO #TABLE_LOCATION_ID
SELECT *
FROM dbo.SPLIT(#LOCATION_ID, ',')
SELECT * FROM #TABLE_LOCATION_ID
DECLARE #TABLE_INVENTORY_ITEM_ID TABLE
(
ID INT,
INVENTORY_ITEM_ID VARCHAR(MAX) -- 2189
)
INSERT INTO #TABLE_INVENTORY_ITEM_ID
SELECT *
FROM dbo.SPLIT(#INVENTORY_ITEM_ID, ',')
SELECT * FROM #TABLE_INVENTORY_ITEM_ID
SELECT DISTINCT LOCATION_ID
FROM #TABLE_LOCATION_ID
IF('FRAMES' = 'FRAMES')
BEGIN
-- declare #LOCATION_ID int ,
--#INVENTORY_ITEM_ID VARCHAR(MAX);
SELECT DISTINCT
I.[UPC_ID],
I.INVENTORY_ITEM_ID,
IP.LOCATION_ID,
PL.LOCATION_NAME,
F.MANUFACTURER,
(CASE WHEN F.BRAND IS NULL THEN '' ELSE F.BRAND END) BRAND,
F.COLOR_NAME,
F.COLOR_TEMPLE,
F.[FRAME_TEMPLE],
F.FRAME_EYE_SIZE,
F.[FRAME_DBL],
F.[COLLECTION] ,
F.MODEL_NO ,
[DESCRIPTION],
IP.RETAIL_PRICE ,
IP.WHOLE_SALE AS WHOLE_SALE_PRICE
FROM
PMS_INVENTORY_ITEM_DETAILS I
INNER JOIN
PMS_INVENTORY_ITEM_PRICING_DETAILS IP ON I.INVENTORY_ITEM_ID = IP.INVENTORY_ITEM_ID
INNER JOIN
PMS_FRAME_SPECIFICATIONS F ON I.INVENTORY_ITEM_ID = F.INVENTORY_ITEM_ID
LEFT JOIN
PRACTICE_LOCATIONS PL ON PL.PRACTICE_LOCATION_ID = IP.LOCATION_ID
LEFT JOIN
[PMS_PURCHASE_ORDER_ITEMS] P ON P.UPC_ID = I.UPC_ID -- MBT#21084 Added by Trupti
LEFT JOIN
[PMS_PURCHASE_ORDERS] PO ON PO. PURCHASE_ORDER_ID = P.PURCHASE_ORDER_ID
WHERE
(IP.LOCATION_ID IN (3) OR #LOCATION_ID IS NULL)
--AND (I.UPC_ID IN (SELECT DISTINCT INVENTORY_ITEM_ID FROM #TABLE_INVENTORY_ITEM_ID ) OR #INVENTORY_ITEM_ID IS NULL)
AND ((I.UPC_ID IN ('01-4001') OR #INVENTORY_ITEM_ID IS NULL)
OR (PO.PO_NO IN (SELECT CAST(DATA AS INTEGER)
FROM dbo.SPLIT(#INVENTORY_ITEM_ID, ',')) OR #INVENTORY_ITEM_ID IS NULL))
AND (I.INVENTORY_CATEGORY = 'FRAMES')
AND (IP.IS_ACTIVE = 1)
AND (I.IS_ACTIVE = 1)
--ORDER BY IP.LAST_SOLD_DATE
--OFFSET (#PAGE_NO - 1) * #PAGE_SIZE ROWS FETCH NEXT #PAGE_SIZE ROWS ONLY
END
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH
END
If I execute the above whole code then I the image below shows output with error
Conversion failed when converting the varchar value '01-4001' to data type int.
But if execute only select query then it works fine. with no error.
My datatype are Varchar(max). Inventory_Item_id is = '01-4001'
If I put inventory_item_id as '2189' then whole execution doesn't throw error.
Response error in network like:
""error":true,"message":"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index""
In table PMS_INVENTORY_ITEM_DETAILS description INVENTORY_ITEM_ID is int length 4 and UPC_ID is varchar length -1.
The error occurs here:
INSERT INTO #TABLE_INVENTORY_ITEM_ID
SELECT * FROM DBO.SPLIT(#INVENTORY_ITEM_ID, ',')
The separator you provide for your split function is , rather than - so the result will be 01-4001 again (rather than the expected 01 and 4001), and converting that to an integer then fails.
To fix, use - as separator.
Hi Thanks for your help.
Issue is resolved
Changes made at line
OR (PO.PO_NO IN (SELECT CAST(DATA AS varchar) FROM DBO.SPLIT(#INVENTORY_ITEM_ID, ',')) OR #INVENTORY_ITEM_ID IS NULL))
CAST(DATA AS INTEGER) updated with CAST(DATA AS varchar)
as parameter #INVENTORY_ITEM_ID is coming as '01-4001' [ - is there so error casting to int ]
As Azure DW is not supporting FOR XML and SELECT variable assignment, is there any other way to convert multiple rows into single row except using CURSOR?
I didn't found any direct method however the below code is working for me.
DECLARE #intColumnCount INT,
#intProcessCount INT,
#varColList VARCHAR(max)
SET #varColList = ''
IF Object_id('tempdb.dbo.#tempColumnNames') IS NOT NULL
BEGIN
DROP TABLE #tempcolumnnames;
END
CREATE TABLE #tempcolumnnames
(
intid INT,
varcolumnnames VARCHAR(256)
)
INSERT INTO #tempcolumnnames
SELECT Row_number()
OVER (
ORDER BY NAME),
NAME
FROM sys.tables
SET #intProcessCount = 1
SET #intColumnCount = (SELECT Count(*)
FROM #tempcolumnnames)
WHILE ( #intProcessCount <= #intColumnCount )
BEGIN
SET #varColList = #varColList + ', '
+ (SELECT varcolumnnames
FROM #tempcolumnnames
WHERE intid = #intProcessCount)
SET #intProcessCount +=1
END
SELECT Stuff(#varColList, 1, 2, '')
Hope this helps someone.
I want to start off by saying that I am brand new to Stored Procedures, and am basically teaching myself how to do them. Any suggestions or advice will be greatly appreciated. I would mail you chocolate if I could.
The Gist: My organization's clients take a survey on their initial visit and on each 6th subsequent visits. We need to know if the individual has shown improvement over time. The way we decided to do this is compare the 1st to the most recent. So if they have been to 18 sessions, it would be the 1st and 3rd surveys that are compared (because they would have completed the survey 3 times over 18 sessions).
I have been able to obtain the "first" score and the "recent" score with two complex, multiple layered-nested select statements inside of one stored procedure. The "first" one is a TOP(1) linking on unique id (DOCID) and then ordered by date. The "recent" one is a TOP(1) linking on unique id (DOCID) and then ordered by date descending. This gets me exactly what I need within each statement, but it does not output what I need correctly which is obviously to the ordering in the statements.
The end result will be to create a Crystal Report with it for grant reporting purposes.
Declare
#StartDate Date,
#EndDate Date,
#First_DOCID Int,
#First_Clientkey Int,
#First_Date_Screening Date,
#First_Composite_Score Float,
#First_Depression_Score Float,
#First_Emotional_Score Float,
#First_Relationship_Score Float,
#Recent_DOCID Int,
#Recent_Clientkey Int,
#Recent_Date_Screening Date,
#Recent_Composite_Score Float,
#Recent_Depression_Score Float,
#Recent_Emotional_Score Float,
#Recent_Relationship_Score Float,
#Difference_Composit_Score Float,
#Difference_Depression_Score Float,
#Difference_Emotional_Score Float,
#Difference_Relationship_Score Float
SET #StartDate = '1/1/2016'
SET #EndDate = '6/1/2016'
BEGIN
SELECT #First_DOCID = CB24_1.OP__DOCID, #First_Date_Screening = CB24_1.Date_Screening, #First_Clientkey = CB24_1.ClientKey, #First_Composite_Score = CB24_1.Composite_score, #First_Depression_Score = CB24_1.Depression_Results, #First_Emotional_Score = CB24_1.Emotional_Results, #First_Relationship_Score = CB24_1.Relationships_Results
FROM FD__CNSLG_BASIS24 AS CB24_1
WHERE (CB24_1.OP__DOCID =
(Select TOP(1) CB24_2.OP__DOCID
...
ORDER BY CB24_2.Date_Screening))
ORDER BY ClientKey DESC
END
BEGIN
SELECT #Recent_DOCID = CB24_1.OP__DOCID, #Recent_Date_Screening = CB24_1.Date_Screening, #Recent_Clientkey = CB24_1.ClientKey, #Recent_Composite_Score = CB24_1.Composite_score, #Recent_Depression_Score = CB24_1.Depression_Results, #Recent_Emotional_Score = CB24_1.Emotional_Results, #Recent_Relationship_Score = CB24_1.Relationships_Results
FROM FD__CNSLG_BASIS24 AS CB24_1
WHERE (CB24_1.OP__DOCID =
(Select TOP(1) CB24_2.OP__DOCID
...
ORDER BY CB24_2.Date_Screening DESC))
ORDER BY ClientKey
END
SET #Difference_Composit_Score = (#Recent_Composite_Score - #First_Composite_Score)
SET #Difference_Depression_Score = (#Recent_Depression_Score - #First_Depression_Score)
SET #Difference_Emotional_Score = (#Recent_Emotional_Score - #First_Emotional_Score)
SET #Difference_Relationship_Score = (#Recent_Relationship_Score - #First_Relationship_Score)
SELECT
#First_DOCID AS First_Docid,
#First_Clientkey AS First_Clientkey,
#First_Date_Screening AS First_Date_Screening,
#First_Composite_Score AS First_Composite_Score,
#First_Depression_Score AS First_Depression_Score,
#First_Emotional_Score AS First_Emotional_Score,
#First_Relationship_Score AS First_Relationship_Score,
#Recent_DOCID AS Recent_DOCID,
#Recent_Clientkey AS Recent_Clientkey,
#Recent_Date_Screening AS Recent_Date_Screening,
#Recent_Composite_Score AS Recent_Composite_Score,
#Recent_Depression_Score AS Recent_Depression_Score,
#Recent_Emotional_Score AS Recent_Emotional_Score,
#Recent_Relationship_Score AS Recent_Relationship_Score,
#Difference_Composit_Score AS Difference_Composit_Score,
#Difference_Depression_Score AS Difference_Depression_Score,
#Difference_Emotional_Score AS Difference_Emotional_Score,
#Difference_Relationship_Score AS Difference_Relationship_Score
In SQL you don't want unnecessary declared variables.
Here's a contrived but reproducible example which utilizes common table expressions and window functions that should get you in the right direction. I created the stored procedure from the template with the necessary input parameters (which in real life you'd like to avoid).
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE dbo.Client_Improvement_Results
(#StartDate DATETIME, #EndDate DATETIME)
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
-- You would never do this in real-life but for a simple reproducible example...
DECLARE #Survey TABLE
(
Clientkey INT,
Date_Screening DATE,
Composite_Score FLOAT
)
INSERT INTO #Survey
VALUES
(1, '2014-04-01', 42.1),
(1, '2014-04-10', 46.1),
(1, '2014-04-20', 48.1),
(2, '2014-05-10', 40.1),
(2, '2014-05-20', 30.1),
(2, '2014-05-30', 10.1)
;
--Use Common Table Expression & Window Functions to ID first/recent visit by client
WITH CTE AS (
SELECT
S.Clientkey
,S.Composite_Score
,S.Date_Screening
,First_Date_Screening = MIN(S.Date_Screening) OVER(PARTITION BY S.Clientkey)
,Recent_Date_Screening = MAX(S.Date_Screening) OVER(PARTITION BY S.Clientkey)
FROM #Survey AS S
)
--Self join of CTE with proper filters
--applied allows you to return differences in one row
SELECT
f.Clientkey
,f.First_Date_Screening
,f.Recent_Date_Screening
,Difference_Score = r.Composite_Score - f.Composite_Score
FROM
CTE AS f --first
INNER JOIN CTE AS r --recent
ON f.Clientkey = r.Clientkey
WHERE
f.Date_Screening = f.First_Date_Screening
AND r.Date_Screening = r.Recent_Date_Screening
END
GO
Here is the solution I came up with after everyone amazing advice.
I want to go back and replace the TOP(1) with another new thing I learned at some point:
select pc.*
from (select pc.*, row_number() over (partition by Clientkey, ProgramAdmitKey order by Date_Screening) as seqnum
from FD__CNSLG_BASIS24 PC) pc
where seqnum = 1
I will have to play with the above script a bit first, however. It doesn't like to be inserted into the larger script below.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
BEGIN
SET NOCOUNT ON;
Declare
#StartDate Date,
#EndDate Date
SET #StartDate = '1/1/2016'
SET #EndDate = '6/1/2016'
WITH CNSL_Clients AS (
SELECT PC_CNT.Clientkey, PC_Cnt.ProgramAdmitKey, PC_Cnt.OP__DOCID
FROM FD__Primary_Client as PC_Cnt
INNER JOIN VW__Cnsl_Session_Count_IndvFamOnly as cnt
ON PC_Cnt.Clientkey = CNT.Clientkey AND PC_Cnt.ProgramAdmitKey = CNT.ProgramAdmitKey
WHERE ((pc_CNT.StartDate between #StartDate AND #EndDate) OR (pc_CNT.StartDate <= #StartDate AND pc_CNT.ENDDate >= #StartDate) OR (pc_CNT.StartDate <= #StartDate AND pc_CNT.ENDDate is null))
AND CNT.SessionCount>=6
),
FIRST_BASIS AS (
SELECT CB24_1.OP__DOCID, CB24_1.Date_Screening, CB24_1.ClientKey, CB24_1.ProgramAdmitKey, CB24_1.Composite_score, CB24_1.Depression_Results,CB24_1.Emotional_Results, CB24_1.Relationships_Results
FROM FD__CNSLG_BASIS24 AS CB24_1
WHERE (CB24_1.OP__DOCID =
(Select TOP(1) CB24_2.OP__DOCID
FROM FD__CNSLG_BASIS24 AS CB24_2
Inner JOIN CNSL_Clients
ON CB24_2.ClientKey = CNSL_Clients.ClientKey AND CB24_2.ProgramAdmitKey = CNSL_Clients.ProgramAdmitKey
WHERE (CB24_1.ClientKey = CB24_2.ClientKey) AND (CB24_1.ProgramAdmitKey = CB24_2.ProgramAdmitKey)
ORDER BY CB24_2.Date_Screening))
),
RECENT_BASIS AS (
SELECT CB24_1.OP__DOCID, CB24_1.Date_Screening, CB24_1.ClientKey, CB24_1.ProgramAdmitKey, CB24_1.Composite_score, CB24_1.Depression_Results,CB24_1.Emotional_Results, CB24_1.Relationships_Results
FROM FD__CNSLG_BASIS24 AS CB24_1
WHERE (CB24_1.OP__DOCID =
(Select TOP(1) CB24_2.OP__DOCID
FROM FD__CNSLG_BASIS24 AS CB24_2
Inner JOIN CNSL_Clients
ON CB24_2.ClientKey = CNSL_Clients.ClientKey AND CB24_2.ProgramAdmitKey = CNSL_Clients.ProgramAdmitKey
WHERE (CB24_1.ClientKey = CB24_2.ClientKey) AND (CB24_1.ProgramAdmitKey = CB24_2.ProgramAdmitKey)
ORDER BY CB24_2.Date_Screening DESC))
)
SELECT F.OP__DOCID AS First_DOCID,R.OP__DOCID as Recent_DOCID,F.ClientKey, F.ProgramAdmitKey, F.Composite_Score AS FComposite_Score, R.Composite_Score as RComposite_Score, Composite_Change = R.Composite_Score - F.Composite_Score, F.Depression_Results AS FDepression_Results, R.Depression_Results AS RDepression_Resluts, Depression_Change = R.Depression_Results - F.Depression_Results, F.Emotional_Results AS FEmotional_Resluts, R.Emotional_Results AS REmotionall_Reslu, Emotional_Change = R.Emotional_Results - F.Emotional_Results, F.Relationships_Results AS FRelationships_Resluts, R.Relationships_Results AS RRelationships_Resluts, Relationship_Change = R.Relationships_Results - F.Relationships_Results
FROM First_basis AS F
FULL Outer JOIN RECENT_BASIS AS R
ON F.ClientKey = R.ClientKey AND F.ProgramAdmitKey = R.ProgramAdmitKey
ORDER BY F.ClientKey
END
GO
I am looking to return a single set of data from my stored proceedure, but the result are returning just the first of the two sets. How do I return just one set of data from the following:
SELECT TOP 1 categoryname, displaypartno
FROM Categories
WHERE catalogid = #CatalogID AND source = #Manufacturer
ORDER BY categoryid DESC
IF ##RowCount=0
BEGIN
SELECT '' AS categoryname, displaypartno
FROM Products
WHERE catalogid = #CatalogID AND source = #Manufacturer
END
Because I need the second SQL to execute only if the first returns no rows, I don't think I can use a UNION.
So you want to select one row if you have a category or all matching product rows:
You were almost there but you need to put both parts in the IF...ELSE statement.
IF EXISTS (SELECT *
FROM Categories
WHERE catalogid = #CatalogID AND source = #Manufacturer)
SELECT TOP 1 categoryname, displaypartno
FROM Categories
WHERE catalogid = #CatalogID AND source = #Manufacturer
ORDER BY categoryid DESC
ELSE
SELECT '' AS categoryname, displaypartno
FROM Products
WHERE catalogid = #CatalogID AND source = #Manufacturer
END
Don't worry about calling it twice unless you have huge demands on this query or are doing something silly elsewhere it won't gause big performance issues.
SELECT TOP 1 categoryname, displaypartno
FROM (
SELECT categoryname, displaypartno, 0 AS ResultPriority
FROM Categories
WHERE catalogid = #CatalogID AND source = #Manufacturer
UNION ALL
SELECT '' AS categoryname, displaypartno, 1 AS ResultPriority
FROM Products
WHERE catalogid = #CatalogID AND source = #Manufacturer
) t
ORDER BY ResultPriority, categoryid DESC
You should use IF NOT EXIST ( ) function.
Create a variable table and add first step's returned items. Then, select all items from variable table you created in IF NOT EXIST condition, and write down your second step.
If you dont create variable table, you select redundant select from Categories table.
Also why you wont use ##ROWCOUNT http://www.johnpapa.net/t-sql-if-not-exists-versus-rowcount/
HERE IS THE BEST EXAMPLE. IF YOU HAVE MULTIPLE QUERY AND IF ONE QUERY
GIVE ERROR, ANOTHER ONE WILL DEFINETELY RUN . LET ASSUME BOTH QUERY
GIVE ERROR.. THERE ARE MULTIPLE DATA ARE PRESENT WHERE SALARY IS
GREATER THAN 4000 AND FOR EMP CODE 7500 THERE IS NO DATA IS PRESENT.
*
Create Or Replace Procedure Proc_Test As
l_Str_1 Varchar2(2000);
l_Str_2 Varchar2(2000);
p_Msg Varchar2(2000);
p_Err_Code Varchar2(2000);
l_Count_1 Number;
l_Count_2 Number;
Begin
l_Str_1 := 'Select Sal From Cmc7 Where Sal > 4000';
l_Str_2 := 'SELECT sal FROM Cmc7 WHERE empno = 7500';
Begin
Execute Immediate l_Str_1
Into l_Count_1;
Dbms_Output.Put_Line(l_Count_1);
Exception
When Too_Many_Rows Then
Dbms_Output.Put_Line('yahoo... many rows');
End;
Begin
Execute Immediate l_Str_2
Into l_Count_2;
Dbms_Output.Put_Line(l_Count_2);
Exception
When No_Data_Found Then
Dbms_Output.Put_Line('sorry...');
End;
Exception
When Others Then
p_Msg := Sqlerrm;
p_Err_Code := Sqlcode;
End;
*
OUT PUT :
yahoo... many rows
sorry...
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.