Saturday, February 25, 2012

query not returning data!

Hi! I have a sql query in stored procedure:
SELECT Salutation + ' ' + FirstName + ' ' + LastName AS fullname

Ok, this returns a value if salutation is not null, but if the salutation is null it doesn't return any value, I was thinking if the saluation is null then I would atleast get the firstname and last name. Any help appreciated on this.

You can us ISNULL or COALESCE to take care the NULL value in your Salutation column before you combine it with firstname and lastname. For example:

SELECT ISNULL(Salutation,'') + ' ' + FirstName + ' ' + LastName AS fullname

Or

SELECT COALESCE(Salutation,'') + ' ' + FirstName + ' ' + LastName AS fullname

|||

To be precise, the query is returning a value. The value is NULL, which in SQL terms is unknown.

So, when you add (concatenate) a known value to an unknown one, what should the result be?

Unknown!

It's analogous to saying, I'm going to add $5 to the money in my pocket. How much money is in my pocket?

You don't know, because you don't know how much money is already in my pocket.

(You don't even know if there is $5 in my pocket - there might be a hole in it. )

You have to be very careful to account for NULL values in the database.

Nothing is less than, greater than, or equal to NULL. Even NULL!

|||

Thank you! It works great now. What does COALESCE mean?

Cheers!

|||

Thank you for the explanation! Make sense.

Query not returning all results

OK, interesting problem I haven't encountered before.
If I do the following query:
Select * from TableA where SequenceNo = 555 and Column = 6 and ClientNo = '123456'
I get 1 row (which is correct).
If I run the same query without the ClientNo specification, I get 4 results,
but Clientno 123456 isn't in the results.
If I run the same query, without the ClientNo specification, without the *
(i.e. manually listing each column), then I get 20 results, which is correct.
Why is this happening? Anyone know how to resolve this?
Manually listing each column is so not an option. Why isn't "Select * from
TableA where SequenceNo = 555 and Column = 6" to returning all 20 valid
results?
FYI: SequenceNo and Column are datatypes int, Clientno is varchar.
I've tried with and without single quotes, and also adding in "where
sequenceno is not null" kind of logic, too.
Argh!!!!!
--
Financial Systems Analyst
CCNA, MCSE, MCSA, MCDBANever mind!
forgot to check to Message tab (doh!), there was a Numeric Value Out Of
Range error.
So, anyone know how to resolve THAT little issue?!?
Thanks!|||Sounds like you've got data corruption or, at least, integrity issues.
Probably because of the use of SELECT * and such.
If you are explicit about everything you do, then there will never be a
question concerning what it is you want.
Leave everything to defaults and you will get ambiguity, which is that start
of corruption.
Sorry to disappoint you, but you need to fix your data or start being more
explicit.
You could try a TOP clause to find the row that is causing you grief and,
then, manually fix the data.
Sincerely,
Anthony Thomas
"Ysandre" <Ysandre@.discussions.microsoft.com> wrote in message
news:773DC2E5-81C5-4AEA-A563-020065BE8943@.microsoft.com...
Never mind!
forgot to check to Message tab (doh!), there was a Numeric Value Out Of
Range error.
So, anyone know how to resolve THAT little issue?!?
Thanks!

Query not returning all results

OK, interesting problem I haven't encountered before.
If I do the following query:
Select * from TableA where SequenceNo = 555 and Column = 6 and ClientNo =
'123456'
I get 1 row (which is correct).
If I run the same query without the ClientNo specification, I get 4 results,
but Clientno 123456 isn't in the results.
If I run the same query, without the ClientNo specification, without the *
(i.e. manually listing each column), then I get 20 results, which is correct
.
Why is this happening? Anyone know how to resolve this?
Manually listing each column is so not an option. Why isn't "Select * from
TableA where SequenceNo = 555 and Column = 6" to returning all 20 valid
results?
FYI: SequenceNo and Column are datatypes int, Clientno is varchar.
I've tried with and without single quotes, and also adding in "where
sequenceno is not null" kind of logic, too.
Argh!!!!!
Financial Systems Analyst
CCNA, MCSE, MCSA, MCDBANever mind!
forgot to check to Message tab (doh!), there was a Numeric Value Out Of
Range error.
So, anyone know how to resolve THAT little issue?!?
Thanks!|||Sounds like you've got data corruption or, at least, integrity issues.
Probably because of the use of SELECT * and such.
If you are explicit about everything you do, then there will never be a
question concerning what it is you want.
Leave everything to defaults and you will get ambiguity, which is that start
of corruption.
Sorry to disappoint you, but you need to fix your data or start being more
explicit.
You could try a TOP clause to find the row that is causing you grief and,
then, manually fix the data.
Sincerely,
Anthony Thomas
"Ysandre" <Ysandre@.discussions.microsoft.com> wrote in message
news:773DC2E5-81C5-4AEA-A563-020065BE8943@.microsoft.com...
Never mind!
forgot to check to Message tab (doh!), there was a Numeric Value Out Of
Range error.
So, anyone know how to resolve THAT little issue?!?
Thanks!

Query not returning all results

OK, interesting problem I haven't encountered before.
If I do the following query:
Select * from TableA where SequenceNo = 555 and Column = 6 and ClientNo =
'123456'
I get 1 row (which is correct).
If I run the same query without the ClientNo specification, I get 4 results,
but Clientno 123456 isn't in the results.
If I run the same query, without the ClientNo specification, without the *
(i.e. manually listing each column), then I get 20 results, which is correct.
Why is this happening? Anyone know how to resolve this?
Manually listing each column is so not an option. Why isn't "Select * from
TableA where SequenceNo = 555 and Column = 6" to returning all 20 valid
results?
FYI: SequenceNo and Column are datatypes int, Clientno is varchar.
I've tried with and without single quotes, and also adding in "where
sequenceno is not null" kind of logic, too.
Argh!!!!!
Financial Systems Analyst
CCNA, MCSE, MCSA, MCDBA
Never mind!
forgot to check to Message tab (doh!), there was a Numeric Value Out Of
Range error.
So, anyone know how to resolve THAT little issue?!?
Thanks!
|||Sounds like you've got data corruption or, at least, integrity issues.
Probably because of the use of SELECT * and such.
If you are explicit about everything you do, then there will never be a
question concerning what it is you want.
Leave everything to defaults and you will get ambiguity, which is that start
of corruption.
Sorry to disappoint you, but you need to fix your data or start being more
explicit.
You could try a TOP clause to find the row that is causing you grief and,
then, manually fix the data.
Sincerely,
Anthony Thomas

"Ysandre" <Ysandre@.discussions.microsoft.com> wrote in message
news:773DC2E5-81C5-4AEA-A563-020065BE8943@.microsoft.com...
Never mind!
forgot to check to Message tab (doh!), there was a Numeric Value Out Of
Range error.
So, anyone know how to resolve THAT little issue?!?
Thanks!

Query not producing correct results and Group By Error

This is what I need in my results:
Current Balance and Account Number should be retrieved where
Current Balance = Sum of rmstranamt - (sum of rmstranamt where rmstrancde is 10)

The Query below gives me a couple of problems

1) It's not producing the correct Current Balance

2) I keep getting these errors with Groupy by:

Column 'rf10.rmstranamt10' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

SELECT rm.rmsacctnum AS [Rms Acct Num],

(sum(rf.rmstranamt) - rf10.rmstranamt10) AS [Current Balance]

FROM RMASTER rm

INNER JOIN

(

SELECT RMSFILENUM, SUM(rmstranamt) AS rmstranamt10

FROM RFINANL

WHERE RMSTRANCDE = '10'

GROUP BY RMSFILENUM

) AS rf10 ON rf10.RMSFILENUM = rm.RMSFILENUM

INNER JOIN

(

SELECT RMSFILENUM, SUM(rmstranamt) AS rmstranamt

FROM RFINANL

GROUP BY RMSFILENUM

) AS rf ON rf.RMSFILENUM = rm.RMSFILENUM

GROUP BY rm.rmsacctnum

The error message is correct as you would have to enclose the rf10.rmstranamnt10 inside a sum() to allow for the aggregation. I always recheck the SQL with an english translation of what I am trying to do. Your descriptive phrase shows the secondary sum, but the T-SQL does not have it.

I hope this helps,

|||

I did as you said and added the sum. I am still getting a Current Balance of 0.00 for an account # I checked when I know for a fact there are a total of 2 positive rmstranamt records in RFINANL with a RMSTRANCDE of 10 so I should have the sume of those in my results for that account number but it's 0.00

This query shows why

SELECT rm.rmsacctnum AS [Rms Acct Num],

sum(rf.rmstranamt) as Sum_rstranamt,

sum(rf10.rmstranamt10) as Sum_rmstranamt_10,

(sum(rf.rmstranamt) - sum(rf10.rmstranamt10)) AS [Current Balance]

FROM RMASTER rm

INNER JOIN

(

SELECT RMSFILENUM, SUM(rmstranamt) AS rmstranamt10

FROM RFINANL

WHERE RMSTRANCDE = '10'

GROUP BY RMSFILENUM

) AS rf10 ON rf10.RMSFILENUM = rm.RMSFILENUM

INNER JOIN

(

SELECT RMSFILENUM, SUM(rmstranamt) AS rmstranamt

FROM RFINANL

GROUP BY RMSFILENUM

) AS rf ON rf.RMSFILENUM = rm.RMSFILENUM

AND rm.rmsacctnum = '4264287999172303'

GROUP BY rm.rmsacctnum

results:

4264287999172303 28789.50 28789.50 0.00

Sum_rstranamt should not be 28789.50 because there are 2 records for that account:

SELECT rm.rmsacctnum AS [Rms Acct Num],

rf.rmstranamt as [Rms rmstranamt],

rf.rmsbalance AS [Rms Balance]

FROM RMASTER rm

INNER JOIN RFINANL rf ON rf.RMSFILENUM = rm.RMSFILENUM

where rm.rmsacctnum = '4264287999172303'

4264287999172303 2878.95 0.00
4264287999172303 25910.55 28789.50

So Sum_rstranamt should be 2878.95 + 25910.55

|||

Here's a second look at what I've sruggled with:

I think we're almost there:
Let's work with account # '4264287999172303'
Query #1 - shows that there are 2 records in the RFINANL table for that account
SELECT rm.rmsacctnum AS [Rms Acct Num],
rf.rmstranamt as [Rms rmstranamt],
rf.rmsbalance AS [Rms Balance]
FROM RMASTER rm
INNER JOIN RFINANL rf ON rf.RMSFILENUM = rm.RMSFILENUM
where rm.rmsacctnum = '4264287999172303'
RESULTS:
4264287999172303 2878.95 0.00
4264287999172303 25910.55 28789.50

Query #2 - shows that there are 2 records in the RFINANL table for that account where RMSTRANCDE = '10'
--
select rm.rmsacctnum AS [Rms Acct Num], rf.rmstranamt
FROM RMASTER rm
INNER JOIN RFINANL rf ON rf.RMSFILENUM = rm.RMSFILENUM
where rf.RMSTRANCDE = '10'
and rm.rmsacctnum = '4264287999172303'
RESULTS:
4264287999172303 2878.95
4264287999172303 25910.55

Now this is what boggles my mind. If we were to take Query #1 and add a sum in it like below, you would get a result of 2878.95 + 25910.55 but I don't.
SELECT rm.rmsacctnum AS [Rms Acct Num],
sum(rf.rmstranamt) as [Rms rmstranamt], < added sum hoping to get 2878.95 + 25910.55
rf.rmsbalance AS [Rms Balance]
FROM RMASTER rm
INNER JOIN RFINANL rf ON rf.RMSFILENUM = rm.RMSFILENUM
where rm.rmsacctnum = '4264287999172303'
GROUP BY rm.rmsacctnum, rf.rmsbalance < but now I'm required to group by any values that do not contain an aggregate function
RESULTS:
4264287999172303 2878.95 0.00
4264287999172303 25910.55 28789.50
Take this a step further, now I add a sum to rf.rmsbalance since at this point I don't know what else do do. I then figure I should get 2878.95 + 25910.55 and 0.00 + 28.789.50 but again, I don't, I end up with both of them havin the same value. I have no idea why:
SELECT rm.rmsacctnum AS [Rms Acct Num],
sum(rf.rmstranamt) as [Rms rmstranamt],
Sum(rf.rmsbalance) AS [Rms Balance] <- Added sum to rf.rmsbalance
FROM RMASTER rm
INNER JOIN RFINANL rf ON rf.RMSFILENUM = rm.RMSFILENUM
where rm.rmsacctnum = '4264287999172303'
GROUP BY rm.rmsacctnum <- took out rf.rmsbalance because it's a sum now in the select
RESULTS:
4264287999172303 28789.50 28789.50

So at this point I'm still not getting this which I am ultimately wanting for each and every account if you we were to figure out the correct syntax:
(2878.95 + 25910.55) - (28789.50) as [Current Balance],
....

Query Not Collating correctly

I have restored an SQL 2000 database in to 2005 Standard edition.

I have several views that are displaying incorrect results though when viewed in SQL Management Studio, and hence back to Excel Word etc....

The view is as follows:

SELECT TOP (100) PERCENT DATEPART(mm, ARV_date) AS Month, COUNT(*) AS Count, SUM(DATEDIFF(mi, ARV_date, RES_date)) AS [Minutes Unresolved],
MAX(DATEDIFF(mi, ARV_date, RES_date)) AS [Max Dur(min)]
FROM dbo.ps_Remedy_Data
WHERE (DATEPART(yy, ARV_date) = DATEPART(yy, GETDATE())) AND (RMDY_Priority = 'Urgent')
GROUP BY DATEPART(mm, ARV_date), RMDY_Priority
ORDER BY Month

When I execute it from Word or Excel the returned data is NOT in Month order...

When I right click the view and say Open View it returns the same unsorted data...

When I right click the view and say MODIFY and do nothing else except EXECUTE the SQL the returned data is in the correct sequence.

This is extremely annoying and can only be described as a bug.

This is a new server running WIN 2003 SP1, with SQL Server 2005 SP1.

Thoughts appreciated, many thanks in advance

regards

Order in views make no sense, though the order by clause is only used within the use of the "TOP Something" clause to ensure that the data is ordered first to give the right data back, using TOP 100 Precent won′t have any effect on that. There is a new blog entry from Kimberly about that, perhaps you shoul have a look on that.

http://www.sqlskills.com/blogs/kimberly/PermaLink.aspx?guid=79de45cb-2da6-4510-ae43-7e5e42e4c02e

The best way would be to treat the view as a column definition and do the order on the view.

HTH, jens Suessmeyer.

http://www.sqlserver2005.de

Monday, February 20, 2012

Query No1

Hi

I have a table Topics which contains Topics Id and Topic Name.

Now i have two strings 'strTopicId' & 'strTopicName'. I need to check whether strTopicId and strTopicName exist in the table or not.


Since TopicId is the Primary Key, so i think a better way to validate would be first to check for the TopicID and then check its corresponding TopicName and see whether it also matches.
You can show me the SP or Query the way it can be done. I think we can return a '1' if its present and a '0' if its not present. I would be very grateful for any help. Thanks a lot.

Regards,

Nab

Hmm, you are asking help to write a stored procedure. Dont you think its not a right place to ask about stored procedures.

Anyway,

CREATEORREPLACEPROCEDURE Sp_Chk_Topic

(

topicID IN"Table_Name"."TopicIDFieldName"%TYPE,

topicName IN"Table_Name"."TopicNameFieldName"%TYPE,

retValueOUTVARCHAR2

)

AS

c_counterNUMBER;

BEGIN

SELECT NVL(COUNT(*),0)INTO c_counterFROMTABLE_NAMEWHERE "topicIDFieldName" = UPPER(topicID) andtopicNameFieldName" = UPPER(topicName)

IF( c_counter<>0)THEN

retValue:='01';--Name matched';

RETURN;

ELSE

retValue:='02';--Name did NOT matched';

RETURN;

ENDIF;

EXCEPTION

WHENOTHERSTHEN

retValue:='03';--'Error Occured getting the data';

RETURN;

END Sp_Chk_Topic;

/

|||

Hi

Thanks a lot, Mr Kumar. I mistakenly posted it here. This should have been in the Sql Sectioin. If it can be moved, it should be.

However i modified ur SP and am still recieving some errors. Could u plz explain the reason of errors.

CREATE PROCEDURE CheckThread
(
@.TopicID IN Topics.TopicId int(4),

@.TopicName IN Topics.TopicName varchar(50),

@.retValue OUT VARCHAR

)

AS

c_counter NUMBER;

BEGIN

SELECT NVL(COUNT(*), 0) INTO c_counter FROM Topics WHERE TopicId = UPPER(TopicID) and TopicName = UPPER(TopicName)

IF( c_counter <> 0 ) THEN

retValue = '01'; --Name matched';

RETURN;

ELSE

retValue = '02'; --Name did NOT matched';

RETURN;

END IF;

EXCEPTION

WHEN OTHERS THEN

retValue = '03'; --'Error Occured getting the data';

RETURN;

END CheckThread;

1)Incorrect Syntax near IN "in line 3"

2)NVL is not a recognized f() name.

3)Incorrect syntax near the keyword 'Then'

4)Line 31: Incorrect syntax near ';'

The errors were much more in the original one. I had to add'@.' and also removed ':' as well. Could u plz inform me of the corrections required. Thanks a lot.

Regards,

NAB

|||You were provided Oracle PL/SQL coding. For SQL Server there are some differences.

1)Incorrect Syntax near IN "in line 3"

In SQL Server stored procedures there is no "IN" keyword. Parameters are assumed to be input parameters unless OUTPUT isspecified. So remove the IN keyword.

2)NVL is not a recognized f() name.

Use ISNULL instead of NVL. although it's not needed here because theCOUNT(*) will return a 0 if no records are found to match the criteria.

3)Incorrect syntax near the keyword 'Then'

In SQL Server stored procedures the THEN keyword is not used, nor isthe END IF keyword, so remove them. When conditional statementsextend for more than one line then enclose them in BEGIN...END blocks.

4)Line 31: Incorrect syntax near ';'

There are no line termination characters in SQL Server stored procedures, so remove them.

Additionally, all variables should be DECLARE'd and all variablesmuch start with an @. character. And SQL Server databases arenormally case-insensitive so the UPPER keyword is likely not needed.


You should be left with something that looks like this:

CREATE PROCEDURE CheckThread
(
@.TopicID int,

@.TopicName varchar(50),

@.retValue varchar(2) OUTPUT

)

AS

DECLARE @.c_counter int


SELECT @.c_counter = COUNT(*) FROM Topics WHERE TopicId = @.TopicID and TopicName = @.TopicName

IF @.@.ERROR <> 0

BEGIN
SELECT @.retValue = '03' --'Error Occured getting the data'
RETURN
END

IF(@.c_counter <> 0 )

SELECT @.retValue = '01' --Name matched'

ELSE

SELECT @.retValue = '02' --Name did NOT matched'


RETURN

That could probably be simplified even further using an EXISTS keyword:

CREATE PROCEDURE CheckThread
(
@.TopicID int,

@.TopicName varchar(50),

@.retValue varchar(2) OUTPUT

)

AS
SELECT @.retValue = '03'

IF EXISTS(SELECT TopicID FROM Topics WHERE TopicId = @.TopicID and TopicName = @.TopicName)

SELECT @.retValue = '01' --Name matched'

ELSE

SELECT @.retValue = '02' --Name did NOT matched'


RETURN



|||

Thanks a lot Tmorton. I think Mr. Kumar never knew what he was posting . I have found a very easier way of doin this and its working perfectly well for my purpose

CREATE PROCEDURE VerifyTopic(@.strTopicId int, @.strTopicName varchar(50))
AS
DECLARE @.Verified int

SELECT @.Verified = 1
FROM Topics
Where TopicId = @.strTopicId AND TopicName = @.strTopicName

If @.Verified = 1
Return 1
else
Return 0
GO

Regards,

NAB

|||

TheNAB wrote:

Thanks a lot Tmorton. I think Mr. Kumar never knew what he was posting . I have found a very easier way of doin this and its working perfectly well for my purpose

lol. You try to help people and this is what you get. Way to go Mr.NAB

By the way, you never mentioned in your original post that you are using SQL server and you posted in Getting Started forum. You simply asked for a damn SP and that too in a wrong forum

Oh yeah, by the way, what you posted is simply a sql server version of my proc, if you know what you are doing

|||

TheNAB wrote:

Thanks a lot Tmorton. I think Mr. Kumar never knew what he was posting .


Kumar knew what he was posting -- he was posting an Oracle storedprocedure. It's not good form to insult those who are trying tohelp you.
I am glad what you have now serves your purpose. I stillrecommend the coding I suggested at the end of my first post, but ifwhat you now have works for you then I guess you have what youneed. Good luck!