user1968541
user1968541

Reputation: 333

Microsoft SQL Server Query is Returning Wrong Result

I have the following code:

$GetUID = $c->query("SELECT UserUID FROM dbo.Users_Master ORDER BY UserID DESC");
$UserUniqueID = $GetUID->fetch(PDO::FETCH_ASSOC);
$UUID = $UserUniqueID['UserUID'];
$NewUUID = $UUID + 1;

This is successfully working, but the problem is something with my query.

It is always entering 12 into my database.

I went to the Microsoft SQL query window and entered:

USE UserData;
SELECT UserUID FROM dbo.Users_Master ORDER BY UserID DESC

and it returned:

11, 17, 15, 19, 16, 18, 10, 13, 12, 14, 3

Which is not exactly ordering by the highest to lowest.

I then went on using:

USE UserData;
SELECT UserUID FROM dbo.Users_Master ORDER BY UserID ASC

Which returned:

3, 14, 12, 13, 10, 18, 16, 19, 15, 17, 11

I want to obtain the higest UserUID and +1 to it.. WHy is my code selecting 11 all the time?

Upvotes: 0

Views: 262

Answers (1)

Taryn
Taryn

Reputation: 247810

Sounds like UserId is not of the datatype int, you can cast() the value to order:

SELECT UserUID 
FROM dbo.Users_Master 
ORDER BY cast(UserID as int) DESC

See SQL Fiddle with Demo

However, the best solution is to alter the datatype in the table to match what is being stored.

To alter the table in SQL Server, you would use:

alter table dbo.Users_Master alter column UserID int;

This would store the data in the correct datatype so you would not have to cast() the value to order it.

Edit #1, based on your comment that UserId is a varchar it seems like you mean to ORDER BY UserUID DESC which is an int

Upvotes: 4

Related Questions