TSQL convert query to return TRUE/FALSE - tsql

How can I convert this query to return TRUE/FALSE values?
SELECT UserID, ResumeID AS PreviouslyViewed FROM MVJ_ProfileViews
WHERE UserID = [User:UserID]
AND ResumeID = [TknParams:ResumeID]

You can cast the result
SELECT CASE WHEN EXISTS (
SELECT UserID, ResumeID AS PreviouslyViewed
FROM MVJ_ProfileViews
WHERE UserID = [User:UserID] AND
ResumeID = [TknParams:ResumeID]
)
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT)
END AS result

IF EXISTS ( SELECT UserID, ResumeID AS PreviouslyViewed
FROM MVJ_ProfileViews
WHERE UserID = [User:UserID] AND
ResumeID = [TknParams:ResumeID])
BEGIN
SELECT 'TRUE' Result
END
ELSE
BEGIN
SELECT 'FALSE' Result
END

Related

Postgres function passing array of strings

I have the Postgres function below to return some info from my DB. I need the p_ic parameter to be able to take an array of
strings.
CREATE OR REPLACE FUNCTION eddie.getinv(
IN p_ic character varying[],
IN p_id character varying)
RETURNS TABLE(cnt bigint, actualid text, actualcompany text, part text, daysinstock double precision, condition text,
ic text, price numeric, stock text, quantity bigint, location text, comments text) AS
$
BEGIN
RETURN QUERY
WITH cte AS (
SELECT
CASE WHEN partnerslist IS NULL OR partnerslist = '' THEN
'XX99'
ELSE
partnerslist
END AS a
FROM support.members WHERE id = p_id
), ctegroup AS
(
SELECT
u.id AS actualid,
(SELECT m.company || ' (' || m.id ||')' FROM support.members m WHERE m.id = u.id) AS actualcompany,
u.itemname AS part,
DATE_PART('day', CURRENT_TIMESTAMP - u.datein::timestamp) AS daysinstock,
TRIM(u.grade)::character varying AS condition,
u.vstockno::text AS stock,
u.holl::text AS ic,
CASE WHEN u.rprice > 0 THEN
u.rprice
ELSE
NULL
END AS price,
u.quantity,
u.location,
u.comments::text
FROM public.net u
WHERE u.holl in (p_ic)
AND visibledate <= now()
AND u.id = ANY(REGEXP_SPLIT_TO_ARRAY(p_id ||','|| (SELECT a FROM cte), ','))
ORDER BY u.itemname, u.id
)
SELECT
COUNT(ctegroup.ic) OVER(PARTITION BY ctegroup.ic ORDER BY ctegroup.ic) AS cnt,
actualid,
MAX(actualcompany) AS actualcompany,
MAX(part) AS part,
MAX(daysinstock) AS daysinstock,
STRING_AGG(condition,',') AS condition,
MAX(ic) AS ic,
MAX(price) AS price,
STRING_AGG(stock,',') AS stock,
SUM(quantity) AS qty,
STRING_AGG(location,',') AS location,
STRING_AGG(comments,';') AS comments
FROM ctegroup
GROUP BY part, actualid, ic
ORDER BY actualid;
END; $
LANGUAGE 'plpgsql';
I am calling it from the pgAdminIII Query window like this:
SELECT * FROM eddie.getinv(array['536-01036','536-01033L','536-01037'], 'N40')
But it is returning this error:
ERROR: operator does not exist: text = character varying[]`
LINE 28: WHERE u.holl in (p_ic)`
How do I fix this, or am I calling it incorrectly? I will be calling it from a PHP API function similar to this:
$id = 'N40';
$ic = array('536-01036','536-01033L','536-01037');
$sql = "SELECT * FROM eddie.getinv(array['". implode("','",$ic)."'], '".$id."');";
try
{
$results = pg_query($sql);
if(pg_num_rows($results) == 0) {
$rows = [];
}
else
{
$data = pg_fetch_all($results);
foreach($data as $item)
{
$rows[$item["ic"]][] = $item;
}
}
pg_free_result($results);
}
catch (Exception $e)
{
$err = array("message"=>$e->getMessage(), "code"=> $e->getCode(), "error"=>$e->__toString().",\n".print_r($_REQUEST, true));
echo json_encode($err);
}
echo json_encode($rows);
It looks like your array is being passed to the function just fine. The problem is in your query.
IN () clauses expect a comma-separated list of values. When you put an array in there, it's interpreted as a one-element list, where the value is the whole array. In other words, u.holl in (p_ic) will check if u.holl is equal to p_ic, and the comparison fails due to the type mismatch.
If you want to test the value against the contents of the array, use u.holl = ANY(p_ic).

Postgres CTE returns null, regexp_split_to_array also empty

WITH cte as (
SELECT partnerlist as a FROM support.members WHERE id = 'BB36'
)
SELECT REGEXP_SPLIT_TO_ARRAY('BB36,'||(SELECT a FROM cte), ',')
The cte returns null, no rows.
Why wouldn't the regexp_split_to_array return [BB36]?
It is used in a where clause like this in my full query:
AND u.id = any(regexp_split_to_array('BB36,'||(SELECT a FROM cte), ','))
Changing the CTE to this made it work:
WITH cte as (
SELECT
CASE WHEN partnerlist IS NULL OR urgpartnerslistori = '' THEN
'XX99'
ELSE
partnerlist
END as a
FROM support.members WHERE id = 'BB36'
)

I cannot manage to insert multiple rows when having multiple fields to get data from

I ran into a problem with regards to trying to insert multiple rows in a table at once. I know it sounds easy, but here is the twist. The procedure itself gets data from a trigger, and the trigger returns a number of rows. So i need to make 1 insert statement to insert those rows and some other data. here is the code:
CREATE PROCEDURE [a01].[usp_raiseFriendAlerts]
(#AccountA UNIQUEIDENTIFIER, #AccountB UNIQUEIDENTIFIER)
AS
BEGIN
DECLARE #typeID TINYINT;
DECLARE #notificationID UNIQUEIDENTIFIER = NEWID();
DECLARE #accountAName NVARCHAR(356);
DECLARE #accountBName NVARCHAR(356);
SET #typeID = ( SELECT typeID
FROM [a01].[tbl_notificationTypes]
WHERE typeName = 'Added friend');
SET #accountAName = ( SELECT accountUsername
FROM [a01].[tbl_userAccounts]
WHERE accountID = #AccountA);
SET #accountBName = ( SELECT accountUsername
FROM [a01].[tbl_userAccounts]
WHERE accountID = #AccountB);
DECLARE #AccountIDZZ UNIQUEIDENTIFIER;
SET #AccountIDZZ = (SELECT friendAccountID
FROM [a01].[udf_getAddedFriendContacts](#AccountA, #AccountB)
EXCEPT
SELECT targetAccountID
FROM [a01].[tbl_blockedAccounts]);
INSERT INTO [a01].[tbl_notificationsInbox] (notificationID, notificationMessage, notificationDate, accountID, typeId)
VALUES (#notificationID, #accountAName + ' is now friends with ' + #accountBName, SYSDATETIMEOFFSET(), #AccountIDZZ , #typeID)
END;
GO
Try this:
CREATE PROCEDURE [a01].[usp_raiseFriendAlerts]
(
#AccountA UNIQUEIDENTIFIER
, #AccountB UNIQUEIDENTIFIER
)
AS
BEGIN
DECLARE #typeID TINYINT
, #notificationID UNIQUEIDENTIFIER = NEWID()
, #accountAName NVARCHAR(356)
, #accountBName NVARCHAR(356)
, #AccountIDZZ UNIQUEIDENTIFIER;
SELECT #typeID = typeID
FROM [a01].[tbl_notificationTypes]
WHERE typeName = 'Added friend';
SELECT #accountAName = accountUsername
FROM [a01].[tbl_userAccounts]
WHERE accountID = #AccountA;
SELECT #accountBName = accountUsername
FROM [a01].[tbl_userAccounts]
WHERE accountID = #AccountB;
INSERT INTO [a01].[tbl_notificationsInbox]
(
notificationID
, notificationMessage
, notificationDate
, accountID
, typeId
)
SELECT #notificationID
, #accountAName + ' is now friends with ' + #accountBName
, SYSDATETIMEOFFSET()
, AIDZZ.accountID
, #typeID
FROM (
SELECT friendAccountID AS 'accountID'
FROM [a01].[udf_getAddedFriendContacts](#AccountA, #AccountB)
EXCEPT
SELECT targetAccountID AS 'accountID'
FROM [a01].[tbl_blockedAccounts]
) AS AIDZZ
END;
GO

Return a value if select returned null

I need to return a value if select returned null. however I found a solution here by putting a query in a sub-query
SELECT COALESCE((SELECT id FROM tbl WHERE id = 9823474), 4) AS id FROM RDB$DATABASE;
The query above would return Null because the value 9823474 does not exist in the table but I want to return a value in that case (for ex 4) so I found the only solution to use select inside sub query and then COALESCE would work, If I did not do that COALESCE will also return Null.
Is it the only solution ?
No, that is not an only way for example
Select first 1 id from (
Select id FROM tbl WHERE id = 9823474
Union All
Select 4 from rdb$database)
Or you can use anonymous procedure http://firebirdsql.su/doku.php?id=execute_block
EXECUTE BLOCK RETURNS ( id integer )
AS
BEGIN
IF ( EXISTS (SELECT * FROM tbl WHERE id = 9823474) )
THEN id = 9823474;
ELSE id = 4;
SUSPEND;
END
... there always are many methods there

TSQL return all records in-case of null inside IN

I want to filter by #campId if not null, or return all if null
This compiles but does not work as intended:
declare #campId int
select *
from cli
where
cu in (
CASE #campId
when null then (select id from [dbo].[camp])
else #campId
end)
if cu is never null
where cu = isnull(#campid, cu)
Try this:
select *
from cli
where
cu in (select isnull(#campId, id) from [dbo].[camp])
This takes advantage of the fact that the select from camp will return #campId if it's not null.
Why not simply use an IF statement?
DECLARE #campId AS INT
IF (#campId IS NULL) BEGIN
SELECT [Column1], [Column2], ...
FROM [dbo].[cli] AS C1
INNER JOIN [dbo].[Camp] AS C2 ON C2.[Id] = C1.[Cu]
END
ELSE BEGIN
SELECT [Column1], [Column2], ...
FROM [dbo].[cli] AS
WHERE [Cu] = #camp
END