|| Data Analyst || [closed] - sql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 days ago.
Improve this question
use warehouse compute_wh;
Use database superstore;
create or replace TABLE TBL_PARAMETER_DIST (
DIST_CODE VARCHAR(50),
CREATED_ON TIMESTAMP_NTZ(9)
);
create or replace TABLE TBL_PARAMETER_DATE (
FROM_DATE TIMESTAMP_NTZ(9),
TO_DATE TIMESTAMP_NTZ(9),
CREATED_ON TIMESTAMP_NTZ(9)
);
INSERT INTO TBL_PARAMETER_DIST (DIST_CODE, CREATED_ON)
VALUES ('8080', '2017-01-08 12:57:18.733');
CREATE OR REPLACE PROCEDURE TEST_PROCEDURE(Partial_Type VARCHAR(10))
AS
BEGIN
BEGIN TRY
DECLARE #Where VARCHAR(MAX) = NULL
IF #Partial_Type = '1'
BEGIN
IF EXISTS (SELECT * FROM tbl_Parameter_Dist)
BEGIN
SET #Where = (select 'A.Dist_Code IN ('||(select listagg(dist_code, ',')
FROM tbl_Parameter_Dist)||')');
END
ELSE
BEGIN
SELECT 'Dist_Code is not exists in table.'
RETURN
END
END
ELSE IF #Partial_Type = '2'
BEGIN
IF EXISTS (SELECT * FROM tbl_Parameter_Date)
BEGIN
SET #Where = (select CONCAT('A.SALE_INV_DATE BETWEEN ''', TO_CHAR(CAST((SELECT TOP 1 From_Date FROM public.tbl_Parameter_Date ORDER BY Created_On DESC) AS date)),''' AND ''',TO_CHAR(CAST((select top 1 to_date from public.tbl_Parameter_Date ORDER BY Created_On DESC) AS date)),''''));
END
ELSE
BEGIN
SET #Where = (select CONCAT('A.SALE_INV_DATE BETWEEN ''', TO_CHAR(CAST((SELECT DATE_FROM_PARTS(EXTRACT(year from current_date),EXTRACT(month from current_date),01)) AS date)),''' AND ''',TO_CHAR(CAST(current_date-1 AS date)),''''));
END
END
ELSE
BEGIN
SET #Where = '1 = 1'
END
SELECT #Where AS OutputString
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() AS ErrorMessage
END CATCH
END;
this code is showing error: SQL compilation error: syntax error line 5 at position 6 unexpected 'DECLARE'. syntax error line 5 at position 14 unexpected '#Where'. syntax error line 5 at position 28 unexpected '('.
SQL compilation error: syntax error line 5 at position 6 unexpected 'DECLARE'. syntax error line 5 at position 14 unexpected '#Where'. syntax error line 5 at position 28 unexpected '('.

Related

SQL Server: use string variable for IN statement [duplicate]

This question already has answers here:
SQL - Stored Procedure with Select Statement using IN (#Variable_CommaDelimitedListOfIDS)
(7 answers)
Closed 4 years ago.
I created a stored procedure that is sent a large string as a single variable. I want to use that string in the IN statement for a query. However, when I try I get NULL result.
ALTER PROCEDURE [dbo].[Validate_Orders]
#failed VARCHAR(4099)
AS
DECLARE #numFailed INT,
#valFailed DECIMAL(19, 2)
SET #numFailed = 0
SET #valFailed = 0
SET #numFailed = LEN(#failed) - LEN( REPLACE(#failed, ',', '') ) + 1
PRINT 'Failed List: ' + #failed
SELECT #valFailed = SUM(Quantity * Price)
FROM Orders
WHERE OrdNum IN (#failed)
PRINT 'Number of Sales Orders that Failed Import: ' + CAST(#numFailed as varchar (10) )
PRINT 'Value of Sales Orders that Failed Import: ' + CONVERT( VARCHAR(64), FORMAT( CASE WHEN #valFailed >= 0 THEN #valFailed ELSE 0 END, 'C') )
GO
EXEC [Validate_OpenSalesOrders] #failed = '''01D89545'',''01D95600'',''01D98436'',''01D98926'',''01D99704'',''01E00297'',''01E00428'',''01E00637'',''01E00787'',''01E01445'',''01E03713'',''01E04232'',''01E04652'',''01E05283'',''01E05304'',''01E05746'',''01E05754'',''01E05824'',''01E05885'',''01E07032'',''01E07103'',''01E07205'',''01E07297'',''01E07665'',''01E07917'',''02A84220'',''03A78284'',''04AA0825'',''04AA0933'',''04AA1134'',''04AA2612'',''04AA2892'',''05A88467'',''05A92716'',''05A93193'',''06A68861'',''07AK9828'',''07AL4784'',''07AL4974'',''07AL9240'',''07AM1817'',''07AM3351'',''07AM4880''...
When it prints the failed list, it prints what I expect:
Failed List: '01D89545','01D95600','01D98436','01D98926','01D99704','01E00297','01E00428','01E00637','01E00787','01E01445','01E03713','01E04232','01E04652','01E05283','01E05304','01E05746','01E05754','01E05824','01E05885','01E07032','01E07103','01E07205','01E07297','01E07665','01E07917','02A84220','03A78284','04AA0825','04AA0933','04AA1134','04AA2612','04AA2892','05A88467','05A92716','05A93193','06A68861','07AK9828','07AL4784','07AL4974','07AL9240','07AM1817','07AM3351','07AM4880','07AM5526','07AM5774','07AM5845','07AM6988','07AM8264','07AM8529','07AM8768','07AN0661','07AN2003','07AN2318','07AN3297','07AN4190','07AN4490','07AN5141','07AN5150','07AN5339','07AN5740','07AN5843','07AN6584','07AN6628','07AN7088','07AN7129','07AN7582'...
I know it's the string throwing it off, but I don't know how to fix it.
Here is a possible solution if you are OK with a risk of SQL injection against your procedure:
CREATE TABLE #t(V MONEY);
DECLARE #SQL VARCHAR(MAX) = 'SELECT SUM(Quantity * Price) FROM Orders WHERE OrdNum IN (' + #failed + ')';
PRINT #SQL
INSERT INTO #t(V) EXEC(#SQL);
SELECT #valFailed = V FROM #t;

SQL IF/ELSE Statement

I'm struggling to understand why the below SQL will not work. I've put a comment (----------Fine up to Here), which is where SQL Server will accept the code when I parse/save the Store proceedure.
The bit below that, it will not take. Still new to SQL so any help would be great.
The error I receive is, Incorrect syntax near the keyword 'ELSE'. The "ELSE" being the one under the comment I mentioned above.
What I also don't understand is, If I change the IF and the BEGIN round, SQL accepts it (below)? I thought ELSE IF was not possible.
----------Fine up to Here
ELSE
IF (#GrabTypeID = '')
BEGIN
****************************************
Code below
**************************************
IF (#GrabtypeID NOT IN (SELECT GRABTYPEID FROM Mytable) AND #GrabtypeID != '') OR
(#Variable1 NOT IN (SELECT ID FROM Mytable) AND #Variable1 !='')
BEGIN
SELECT #ErrorMessage ='The GrabTypeID or the ID is an invalid value'
RAISERROR (#ErrorMessage, 16, 1)
PRINT 'Invalid Parameters passed Through'
RETURN
END
ELSE
BEGIN
IF (#GrabtypeID ! ='')
TRUNCATE TABLE Datatable1
TRUNCATE TABLE Datatable2
INSERT Datatable1
SELECT * FROM Referencetable1
INSERT Datatable2
SELECT * FROM REFERENCETABLE2
END
----------Fine up to Here
ELSE
BEGIN
IF (#GrabTypeID = '')
TRUNCATE TABLE Datatable1
TRUNCATE TABLE Datatable2
INSERT Datatable1
SELECT * FROM REFERENCETABLE1 WHERE CATEGORY = 4
INSERT Datatable2
SELECT * FROM REFERENCETABLE2 WHERE CATEGORY = 4
END
GO
Your format is a little weird. You could make it work the way you have it, but I think it would be better to use this format:
IF expression
BEGIN
SELECT
END
ELSE IF expression
BEGIN
SELECT
END
ELSE IF expression
BEGIN
SELECT
END
Specifically, change this:
ELSE
BEGIN
IF (#GrabtypeID ! ='')
To this (in both places):
ELSE IF (#GrabtypeID ! ='')
BEGIN

incorrect syntax near the keyword 'end'. sql [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
ALTER procedure [dbo].[proc_PostVisitCountInsert](
#postCount bigint,
#postID bigint)
as
Begin
if not exists(select * from PostVisitCount where postID=#postID)
Begin
Insert into PostVisitCount(postcount,postID) values(#postCount, #postID)
end
else
Begin
--Query for Update PostVisitCount
Declare #count bigint
Set #count=(select postcount from PostVisitCount where postID=#postID)
Update PostVisitCount set postcount=(#count+1), postID=#postID
End
end --Error getting at this place
When I try to execute the query, I'm getting error with these query. I don't understand what is wrong with this query any one helps me to figure out what did I do wrong.
The Begin End for ELSE does not contain any statement (it is actually commented out). That is the reason for the error. The following will work
ALTER procedure [dbo].[proc_PostVisitCountInsert](
#postCount bigint,
#postID bigint)
as
Begin
if not exists(select * from PostVisitCount where postID=#postID)
Begin
Insert into PostVisitCount(postcount,postID) values(#postCount, #postID)
end
else
Begin
Query for Update PostVisitCount
End
end --Error getting at this place
#user6503334: I am not sure whether my post would fix your issue but you can change the "else" part like the below since I felt there is something logically missing in your update statement. I have done a couple of changes in the else part. You should add where clause otherwise all the rows would be updated.
ALTER PROCEDURE [dbo].[proc_PostVisitCountInsert] (
#postCount BIGINT
,#postID BIGINT
)
AS
BEGIN
IF NOT EXISTS (
SELECT 1
FROM PostVisitCount
WHERE postID = #postID
)
BEGIN
INSERT INTO PostVisitCount (
postcount
,postID
)
VALUES (
#postCount
,#postID
)
END
ELSE
BEGIN
--Query for Update PostVisitCount
DECLARE #count BIGINT
SET #count = (
SELECT sum(postcount) + 1
FROM PostVisitCount
WHERE postID = #postID
)
UPDATE PostVisitCount
SET postcount = #count
WHERE postID = #postID
END
END
Since the one valid answer was given in a comment and not everybody reads those, the script should look like this:
ALTER procedure [dbo].[proc_PostVisitCountInsert](
#postCount bigint,
#postID bigint
)
as
Begin
if not exists (select *
from PostVisitCount
where postId = #postId)
Begin
insert into PostVisitCount(postcount,postID) values(#postCount, #postID)
end
else
Begin
--Query for Update PostVisitCount
update PostVisitCount set postcount = postcount + 1 where postID = #postID
End
end
Probably this should work.
ALTER procedure [dbo].[proc_PostVisitCountInsert](
#postCount bigint,
#postID bigint)
as
Begin
if not exists(select * from PostVisitCount where postID=#postID)
Insert into PostVisitCount(postcount,postID) values(#postCount, #postID)
else
--Query for Update PostVisitCount
end --Error getting at this place

Looping within SQL(ite) SELECT

The following SQLite query works:
SELECT Name,
(CASE
WHEN P1=1 THEN 1
WHEN P2=1 THEN 2
WHEN P3=1 THEN 3
WHEN P4=1 THEN 4
WHEN P5=1 THEN 5
ELSE NULL
END) AS Col
FROM table
but is there a way to loop then WHEN statements? Following this question and answer I tried:
SELECT Nachname, Vorname,
(CASE
DECLARE #i int = 0
WHILE #i < 5 BEGIN
SET #i = #i + 1
WHEN P#i=1 THEN #i
END
END) AS Col
FROM table
but this didn't work, saying: error in statement: near "#i": syntax error.
For full information I am applying this statement through a sqldf function on R.
SQLite has no mechanism to create column names dynamically.
You have to list all columns by hand, or create the SQL query dynamically from your program.

expression of non-boolean type specified when merging?

I have the following code to create a stored procedure, but I seem to be getting a lot of errors below this line:
ON (Target.Email = Source.Email AND Target.PromoName = Source.PromoName)
The error on this line is "expression of non-boolean type specified".
What am I doing wrong here?
CREATE PROCEDURE [dbo].InsertUpdateBasicPromoEntry
#Email nvarchar(100)
,#PromoName varchar(100)
,#MaxEntries tinyint
AS
BEGIN
SET NOCOUNT ON;
MERGE [dbo].[BasicCodePromoEntries] AS Target
USING (
SELECT
#Email as Email
,#PromoName as PromoName
) AS Source
ON (Target.Email = Source.Email AND Target.PromoName = Source.PromoName)
WHEN MATCHED
THEN
BEGIN
IF Target.PeriodExpires < GETDATE()
BEGIN
UPDATE SET
Target.PeriodExpires = GETDATE()
,Target.PeriodEntries = 1
END
ELSE IF Target.PeriodExpires > GETDATE() AND Target.PeriodEntries < #MaxEntries
BEGIN
UPDATE SET
Target.PeriodEntries = Target.PeriodEntries + 1
END
ELSE
BEGIN
RETURN 1
END
RETURN 0
END
WHEN NOT MATCHED BY Target
THEN
BEGIN
INSERT INTO Target (Email, PromoName, PeriodEntries, PeriodExpires) VALUES (#Email, #PromoName, 1, DATEADD(day, 1, GETDATE()))
RETURN 0
END
END
PS: Every BEGIN and END is underlined, saying, incorrect syntax near...