Not getting null values when no data available - sql-server-2008

In my stored procedure, I declared #account_id, which sets as per the serial number.
if there are no matching records for the SERIAL_NUMBER, #account_id is not getting NULL value. WHERE condition is mentioned in section B.
So, when I pass invalid serial number, still records are coming which shouldn't. Please guide me to solve this issue.
Section A:
DECLARE #Account_ID INT
SELECT #Account_ID = ACCOUNT_ID FROM T_ACCOUNT WITH (NOLOCK) WHERE SERIAL_NUMBER = #Serial_Number
Section B:
WHERE
(#Account_ID IS NULL OR Acct.ACCOUNT_ID = #Account_ID)

Try this,
Section A:
DECLARE #Account_ID INT
SELECT #Account_ID = ACCOUNT_ID FROM T_ACCOUNT WITH (NOLOCK) WHERE SERIAL_NUMBER = #Serial_Number
Section B:
WHERE
Acct.ACCOUNT_ID = #Account_ID
In your query you are using OR condition where your query return all the records even if the variable #AccountId is NULL.

Related

Count is not being stored in variable in MySQL Trigger

I am getting very weird issue in MySQL trigger.
Count value is not being stored into variable. Below is my code.
DECLARE user_cnt INTEGER;
DECLARE company_id INTEGER;
...
SELECT IF(COUNT(id) > 0, COUNT(id), -1) INTO #user_cnt
FROM user
WHERE user_type = 'admin' AND `status` = 'enabled' AND company_id = #company_id;
Whereas #company_id has a valid integer value.
Here #user_cnt is always returning -1 as value.
What can be done? Am I missing something?

SQL: GROUP BY Clause for Comma Separated Values

Can anyone help me how to check duplicate values from multiple comma separated value. I have a customer table and in that one can insert multiple comma separated contact number and I want to check duplicate values from last five digits.For reference check screenshot attached and the required output is
contact_no. count
97359506775 -- 2
390558073039-- 1
904462511251-- 1
I would advise you to redesign your database schema, if possible. Your current database violates First Normal Form since your attribute values are not indivisible.
Create a table where id together with a single phone number constitutes a key, this constraint enforces that no duplicates occur.
I don't remember much but I will try to put the idea (it's something which I had used a long time ago):
Create a table value function which will take the id and phone number as input and then generate a table with id and phone numbers and return it.
Use this function in query passing id and phone number. The query is such that for each id you get as many rows as the phone numbers. CROSS APPLY/OUTER APPLY needs to be used.
Then you can check for the duplicates.
The function would be something like this:
CREATE FUNCTION udf_PhoneNumbers
(
#Id INT
,#Phone VARCHAR(300)
) RETURNS #PhonesTable TABLE(Id INT, Phone VARCHAR(50))
BEGIN
DECLARE #CommaIndex INT
DECLARE #CurrentPosition INT
DECLARE #StringLength INT
DECLARE #PhoneNumber VARCHAR(50)
SELECT #StringLength = LEN(#Phone)
SELECT #CommaIndex = -1
SELECT #CurrentPosition = 1
--index is 1 based
WHILE #CommaIndex < #StringLength AND #CommaIndex <> 0
BEGIN
SELECT #CommaIndex = CHARINDEX(',', #Phone, #CurrentPosition)
IF #CommaIndex <> 0
SELECT #PhoneNumber = SUBSTRING(#Phone, #CurrentPosition, #CommaIndex - #CurrentPosition)
ELSE
SELECT #PhoneNumber = SUBSTRING(#Phone, #CurrentPosition, #StringLength - #CurrentPosition + 1)
SELECT #CurrentPosition = #CommaIndex + 1
INSERT INTO #UsersTable VALUES(#Id, #PhoneNumber)
END
RETURN
END
Then run CROSS APPLY query:
SELECT
U.*
,UD.*
FROM yourtable U CROSS APPLY udf_PhoneNumbers(Userid, Phone) UD
This will give you the table on which you can run query to find duplicate.

SQLserver Store Column as variable and loop through it

I am still pretty new to SQL server and I am not sure how to do this. I am first creating a table with just the IDs I need:
SELECT DISTINCT
ID_NUMBER
INTO
#IDlist
FROM
V_Rpt_IDs WITH (NOLOCK)
WHERE
ID_NUMBER in (
'1000764169'
,'1005870537'
,'1008053856'
,'1008054376'
,'1008410224'
,'1008411317'
,'1008465318'
,'1008466074'
,'1008492967'
,'1010546872'
,'1010554301')
Select * from #IDlist
And this works fine. But now I would like to declare a variable to represent this column, or each item in this column, so that I can then do a loop where it loops through each ID Number and returns information about each one and then presents all of that as a table. Here is my shot at that:
Declare #IDNumber as VARCHAR(10)
Set #IDNumber = #IDlist.ID_NUMBER
DECLARE #cnt INT = 0
WHILE #cnt < (Select Count(*) From #IDlist)
BEGIN
SELECT TOP 1
NAME
,MAILING_ADDRESS_1
,MAILING_ADDRESS_CITY
,MAILING_STATE
,MAILING_ZIP
from
V_Rpt_Info
WHERE
ID_NUMBER = #IDNumber
SET #cnt = #cnt + 1
END
DROP TABLE #IDlist
But when I Set the #IDNumber variable to #IDlist.ID_NUMBER, it says The multi-part identifier "#IDlist.ID_NUMBER" could not be bound.
How do I do this?
Thanks
The way you set the variable is not correct, SQL doesn't know which ID_NUMBER row it should assign to the #IDNumber variable.
You should do this with a SELECT, for example
SET #IDNumber = SELECT TOP 1 ID_NUMBER FROM #IDlist
But, why would you like to loop through this temporary table this way ? Isn't it possible to join the necessary data with this table instead of doing it one by one ?
Rather then loop through, you're going to want to join your ID table to your V_Rpt_Info view.
SELECT
NAME
, MAILING_ADDRESS_1
, MAILING_ADDRESS_CITY
, MAILING_STATE
, MAILING_ZIP
FROM V_Rpt_Info V
INNER JOIN #IDlist ID
ON V.ID_NUMBER = ID.ID_NUMBER

MySQL Stored Proc Variable returns NULL

I have a stored proc that is setting one of the variables to NULL, though the query returns results.
Here is the SP:
CREATE DEFINER=`xxx`#`localhost` PROCEDURE `test`(IN CLIENT_ID INT)
BEGIN
DECLARE BEGIN_RANGE INT UNSIGNED DEFAULT 0;
select client_id into #CLIENT_ID3 from clients where
client_id = CLIENT_ID limit 1;
SET #BEGIN_RANGE = (select var_value from counter where var_name =
'latest_report_id_summarized' limit 1);
SELECT latest_invoice_id into #LATEST_INVOICE_ID from
SQL_AuditPro.clients where client_id = CLIENT_ID;
END
when I run the sp, then select the results :
select #CLIENT_ID3,#BEGIN_RANGE,#LATEST_INVOICE_ID;
I get :
12345,2342342234,NULL
I have also tried:
CREATE DEFINER=`xxx`#`localhost` PROCEDURE `test`(IN CLIENT_ID INT)
BEGIN
DECLARE BEGIN_RANGE INT UNSIGNED DEFAULT 0;
select client_id into #CLIENT_ID3 from clients
where client_id = CLIENT_ID limit 1;
SET #BEGIN_RANGE = (select var_value from counter where var_name =
'latest_report_id_summarized' limit 1);
SET #LATEST_INVOICE_ID = (SELECT latest_invoice_id from
SQL_AuditPro.clients where client_id = CLIENT_ID);
END
Same result. Obviously I don't need to SET #CLIENT_ID3 it was just in there for testing. Any ideas why this won't set the variable? When I run this query by itself I get a result, and if I run :
SELECT latest_invoice_id into #LATEST_INVOICE_ID from
SQL_AuditPro.clients where client_id = 12345;
select #LATEST_INVOICE_ID;
I get :
2342342234
I have tried declaring the variable, not declaring it, and it just seems like this variable seems to fall out of scope after the SP completes, yet the other two don't.
Thanks for any help you may be able to provide.
select client_id into #CLIENT_ID3 from clients where client_id = CLIENT_ID limit 1;
^---- missing #
SET #LATEST_INVOICE_ID = (SELECT [..snip..] where client_id = CLIENT_ID);
^--missing # as well
As written, both'll be intepreted as a self-equality test, e.g. where 1 = 1. There's no way for mysql to know that the client_id on EITHER side of the = is supposed to be the parameter you passed in to the stored proc, so both client_id will be treated as field names.
Since the second query is likely to return MULTIPLE rows of data, and you're trying to assign that result into a single variable, you'll get NULL as the result.
When you have defined arguments names to match with one or more of a table columns, then in your SQL statements you must use column qualifiers to differentiate with argument names. Otherwise, they will be treated and replaced as and by argument values;
See SQL Fiddle Example
In your case, as the condition client_id = CLIENT_ID was causing to (possibly) fetch multiple records, they are not assignable to a variable of non cursor type. Hence a NULL, the default value for user defined variables, was returned.
Change your procedure body as below:
CREATE DEFINER=`xxx`#`localhost` PROCEDURE `test`(IN CLIENT_ID INT)
BEGIN
DECLARE BEGIN_RANGE INT UNSIGNED DEFAULT 0;
select c.client_id into #CLIENT_ID3
from clients c
where c.client_id = CLIENT_ID limit 1;
SET #BEGIN_RANGE =
(select var_value
from counter
where var_name = 'latest_report_id_summarized' limit 1);
SET #LATEST_INVOICE_ID =
(SELECT c.latest_invoice_id
from SQL_AuditPro.clients c
where c.client_id = CLIENT_ID);
END

MySql Stored Proc - Select query returns null if using where clause not included in select list?

I have a proc that simply contains the following:
SELECT Col1, Col2 FROM table WHERE Id = 1;
This always returns null values. If I change the statement to:
SELECT Id, Col1, Cold2 FROM table WHERE Id = 1;
The row gets returned as expected. Does mySql procs demand that the where clause columns appear in the select list? It doesn't have this behaviour when running the SQL directly in phpMyAdmin.
Here's the code in question:
CREATE PROCEDURE sp_player_login
(
IN
userGraphId INT(11),
authToken TEXT
)
BEGIN
DECLARE playerId INT;
DECLARE newPlayer BOOLEAN DEFAULT FALSE;
SELECT Id INTO playerId FROM player WHERE FacebookGraphId = userGraphId;
If playerId IS NULL THEN
-- Create the player.
SET newPlayer = TRUE;
-- Get new player defaults.
SELECT NewPlayerTurns, NewPlayerMoney, NewPlayerMorale, NewPlayerMissilePower FROM defaults WHERE Id = 1;
END IF;
END #
The second SELECT NewPlayerTurns... is the one that returns null values if I don't specify the Id column in the select clause. If I remove the first SELECT Id INTO ...the second query works without the Id in the select clause...? confused