Query with "incorrect syntax near the keyword 'CASE" - tsql

I have a code:
DECLARE #a char(4)
Select #a=field_name
FROM table_name
where field='abc'
CASE #a
WHEN '2016' THEN
SELECT 'YES'
ELSE
SELECT 'No'
END CASE
The error is:
Incorrect syntax near keyword 'CASE'
What is the problem?

This works with MSSQL:
DECLARE #a char(4)
Select #a=field_name
FROM table_name
where field='abc'
IF #a = '2016'
SELECT 'YES'
ELSE
SELECT 'No'
Or use this:
SELECT
CASE WHEN field_name = '2016' THEN 'YES' ELSE 'No' END
FROM table_name
WHERE field='abc'

Related

Postgres function returning a string from a select statement

I am trying to get this function to return a string that comes from the SELECT statement.
CREATE OR REPLACE FUNCTION dbo.fnRepID (pram_ID BIGINT)
RETURNS varchar AS $$
DECLARE
pram varchar := '';
BEGIN
SELECT pram = pram || (Case COALESCE(a.Name, '') WHEN '' THEN '' ELSE b.Name || ' - ' END )
|| (Case COALESCE(b.Name, '' ) WHEN '' THEN '' ELSE b.Name || ' - ' END )
|| f.NAME || ';'
FROM dbo.ClassRelationship a
LEFT JOIN dbo.ClassRelationship b ON a.ParentClassID = b.ClassID and b.Type = 2 and a.Type = 1;
RETURN pram;
END;
$$ LANGUAGE plpgsql;
GRANT EXECUTE ON FUNCTION dbo.fnRepID (BIGINT) TO "postgres";
And this function creation seem to go through just fine, now I want to call this function with 0 as pram_ID but it's saying this basically no matter what I do.
ERROR: query has no destination for result data
HINT: If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT: PL/pgSQL function dbo.fnrepid(bigint) line 5 at SQL statement
SQL statement "SELECT dbo.fnRepID(0)"
PL/pgSQL function inline_code_block line 2 at PERFORM
SQL state: 42601
I have tried a DO PERFORM block as I have seen similar examples
DO $$ BEGIN PERFORM dbo.fnRepID(0); END $$;but I basically want to get the return value from this function somehow. If there's anything wrong with my procedures please let me know, as I am new to postgres. Thank you.
Edit: Would the following work if I want to append each row of the results into the same var? (can I use select into with the variable on both sides to append to itself?)
CREATE OR REPLACE FUNCTION dbo.fnRepID (pram_ID BIGINT)
RETURNS varchar AS $$
DECLARE
pram varchar := '';
BEGIN
SELECT pram || (Case COALESCE(a.Name, '') WHEN '' THEN '' ELSE b.Name || ' - ' END )
|| (Case COALESCE(b.Name, '' ) WHEN '' THEN '' ELSE b.Name || ' - ' END )
|| f.NAME || ';' INTO pram
FROM dbo.ClassRelationship a
LEFT JOIN dbo.ClassRelationship b ON a.ParentClassID = b.ClassID and b.Type = 2 and a.Type = 1;
RETURN pram;
END;
$$ LANGUAGE plpgsql;
GRANT EXECUTE ON FUNCTION dbo.fnRepID (BIGINT) TO "postgres";
You're doing
SELECT pram = (…) FROM dbo.ClassRelationship a …;
where (…) is an expression that is evaluated and then compared to the current value of pram (which was initialised to an empty string). The query does nothing else, there is no destination for this boolean value (comparison result) it computes, you're getting an error.
You most likely meant to either perform an assignment
pram = SELECT (…) FROM dbo.ClassRelationship a …;
or use an INTO clause:
SELECT (…) INTO pram FROM dbo.ClassRelationship a …;
Notice that you don't even need pl/pgsql to do this. A plain sql function would do as well:
CREATE OR REPLACE FUNCTION dbo.fnRepID(pram_ID BIGINT) RETURNS varchar
LANGUAGE sql
STABLE
RETURN (
SELECT
'' ||
(CASE COALESCE(a.Name, '') WHEN '' THEN '' ELSE b.Name || ' - ' END) ||
(CASE COALESCE(b.Name, '' ) WHEN '' THEN '' ELSE b.Name || ' - ' END) ||
f.NAME ||
';'
FROM dbo.ClassRelationship a
LEFT JOIN dbo.ClassRelationship b ON a.ParentClassID = b.ClassID AND b.Type = 2 AND a.Type = 1
);

Why cant I write select clause in if statement?

I am trying to active something below in AmazonRedshift:
IF
(SELECT
count(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'ABC'
AND column_name = 'COLUMN'
and table_schema ='SCHEMA'
) > 0
THEN
RAISE INFO 'table present';
ELSE
RAISE INFO 'Table not present';
END IF;
I am getting error below:
Invalid operation: syntax error at or near "IF"
What am I doing wrong?
You can try this. I think it will work.
DECLARE #counter bigint=0;
SELECT #counter = count(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'ABC' AND column_name = 'COLUMN' and table_schema ='SCHEMA'
IF (#counter) > 0
BEGIN
print('Table exists');
END
ELSE
BEGIN
print('Table does not exists');
END

How to remove duplicate words from a string comparing to other string in SQL

I need to check string2 if there are words that I already have in string1 and remove those.
declare #Text1 nvarchar(500) = 'apple, orange, pear'
declare #Text2 nvarchar(500) = 'banana, apple'
The output should be 'banana'
Edit: I just realized I made the question not properly.
So, this is right:
DECLARE #Tab TABLE (Ingredients nvarchar(500))
insert #Tab select 'apple, orange, pear'
insert #Tab select 'banana, apple'
insert #Tab select 'pear, mango'
declare #Ingredients nvarchar(4000) = ''
select #Ingredients = #Ingredients + value + ',' from #Tab cross apply STRING_SPLIT(Ingredients, ',')
SELECT #Ingredients
current result:
apple,orange,pear,banana,apple,pear,mango,
expected result:
apple,orange,pear,banana,mango,
So if that is the case I would like to suggest you to create a function:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION GetUniqueValues
(
#LIST AS NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #POS INT
DECLARE #LEN INT
DECLARE #VALUE NVARCHAR(MAX)
SET #POS = 0
SET #LEN = 0
DECLARE #RESULT NVARCHAR(MAX) = ''
WHILE CHARINDEX(',', #LIST, #POS + 1) > 0
BEGIN
SET #LEN = CHARINDEX(',', #LIST, #POS + 1) - #POS
SET #VALUE = RTRIM(LTRIM(SUBSTRING(#LIST, #POS, #LEN)))
IF (CHARINDEX(#VALUE, #RESULT) = 0)
BEGIN
IF (LEN(RTRIM(LTRIM(#RESULT))) = 0)
BEGIN
SET #RESULT = #VALUE
END
ELSE
BEGIN
SET #RESULT = #RESULT + ', ' + #VALUE
END
END
SET #POS = CHARINDEX(',', #LIST, #POS + #LEN) +1
END
RETURN #RESULT
END
GO
You can use this function like this based on you example:
SELECT dbo.GetUniqueValues(#Ingredients)
Expected result
apple, orange, pear, banana, mango
you can use something like this:
DECLARE #Text1 NVARCHAR(500)= 'apple, orange, pear';
DECLARE #Text2 NVARCHAR(500)= 'banana, apple, cucumber, pear';
--convert to xml for further split using nodes
declare #xmlText1 as xml = convert(xml, Concat('<a>',replace(#Text1,',','</a><a>'),'</a>'))
declare #xmlText2 as xml = convert(xml, Concat('<a>',replace(#Text2,',','</a><a>'),'</a>'))
--remove duplicates from #text2 that exist in #text1
;with cte (val) as (
select ', ' + value
from (
select ltrim(n.value('.', 'VARCHAR(10)')) AS value
from #xmlText2.nodes('a') as t(n)
except
select ltrim(n.value('.', 'VARCHAR(10)')) AS value
from #xmlText1.nodes('a') as t(n)
) as t
for xml path ('')
)
-- reassign #text2
select #Text2 = stuff(val,1,1,'') from cte
--output
select #Text2 as newText2
result
You can try this:
DECLARE #Text1 NVARCHAR(500)= 'apple, orange, pear';
DECLARE #Text2 NVARCHAR(500)= 'banana, apple';
SELECT *
INTO #temp
FROM
(
SELECT *
FROM fn_split(#Text1, ',')
) a;
SELECT *
INTO #temp1
FROM
(
SELECT *
FROM fn_split(#Text2, ',')
) b;
SELECT item
FROM #temp1 a
WHERE NOT EXISTS
(
SELECT item
FROM #temp b
WHERE a.item = b.item
);

sql get values inside variables conditionally

I'm trying to get values in variables based on condition as below,
DECLARE #HP INT,#PP INT;
SELECT CASE COLUMN_1
WHEN 'VAL1' THEN SELECT #HP = COLUMN_CD
WHEN 'VAL2' THEN SELECT #PP = COLUMN_CD
END
FROM TBL
no success. how can i do this?
Note: here COLUMN_1 is UNIQUE
TheCASE..WHEN structure should return with a scalar value, not with a resultset. SELECT statement returns a resultset. (The SELECT #HP = COLUMN_CD parts)
You have to assign the values to the variables individually like this:
DECLARE #HP INT,#PP INT;
SELECT
#HP = CASE WHEN COLUMN_1 = 'VAL1' THEN COLUMN_CD ELSE #HP END
, #PP = CASE WHEN COLUMN_1 = 'VAL2' THEN COLUMN_CD ELSE #PP END
FROM
TBL
OR if you do not want to preserve the original value of the variables, you can replace the #HP and #PP in the ELSE part to NULL:
DECLARE #HP INT,#PP INT;
SELECT
#HP = CASE WHEN COLUMN_1 = 'VAL1' THEN COLUMN_CD ELSE NULL END
, #PP = CASE WHEN COLUMN_1 = 'VAL2' THEN COLUMN_CD ELSE NULL END
FROM
TBL

How do I get the return value from a CASE statement as a dynamic SQL query?

DECLARE #command = 'SELECT CASE WHEN ( SELECT COUNT(*)
FROM [table] WITH ( NOLOCK )
WHERE DATEDIFF(minute, systemupdatedtimestamp, GETDATE()) < 10
) > 0 THEN 0
ELSE 1
END'
Now I need to get the 'return value' of the above command (0 or 1).
EXEC(#commnad)
How do I get the return value from the above?
I tried
SET #ReturnValue = EXEC(#command)
but no luck.
use sp_executesql
in your case it is something like:
declare #myOut bit
declare #SQLString nvarchar(500)
set #SQLString = N'SELECT #myOutValue = CASE WHEN ( SELECT COUNT(*)
FROM [table] WITH ( NOLOCK )
WHERE DATEDIFF(minute, systemupdatedtimestamp, GETDATE()) < 10
) > 0 THEN 0
ELSE 1
END'
declare #ParmDefinition nvarchar(500)
set #ParmDefinition = N'#myOutValue bit OUTPUT'
EXECUTE sp_executesql #SQLString, #ParmDefinition, #myOutValue = #myOut OUTPUT
select #myOut
Update:
To follow up on you comment. If you do not want to modify the original string containing your sql command (e.g. it is used in other places etc) you can wrap that command inside a new string something like:
#SQLString = 'select #myOutValue = (' + #yourOrigSqlCommand + ')'
And call sp_executesql in the same way as above.
I believe this solves your problem.
DECLARE #command nvarchar(max) = 'SELECT CASE WHEN ( SELECT COUNT(*)
FROM [table] WITH ( NOLOCK )
WHERE DATEDIFF(minute, systemupdatedtimestamp, GETDATE()) < 10
) > 0 THEN 0
ELSE 1
END'
exec sp_executesql #command