简体   繁体   中英

Create a procedure to return 32bit ID(nvarchar) with date time when user logs in to a web application

I am trying to write a Microsoft SQL server procedure to return a 32bit ID and date time when the user logs in to an application through a website.I have PHP on the front end to call for the procedure. The Id would be the session used to evaluate the session of the user and update that in the table.

I am having a problem coming up with a procedure that can generate a 32bit id and date time to return to PHP call.I am new to MS SQL I need help.

For your Integer:

You can use the built in RAND() function to generate a positive decimal between 0 and 1 and multiply that by the max 32 bit INT value 2147483647 .

Example :

If you're using a Scalar-Valued Function:

...
DECLARE @return INT

SET @return = FLOOR(RAND() * 2147483647)

RETURN(@return)

For your Datetime:

You would have to use a date range that you would want to generate a date for. Additionally, you would have to decide the increment you would want to generate that datetime in (by DAY , SECOND , etc.). You can also use RAND() similar to the previous example with INT .

Example:

Also assuming you're using a Scalar-Valued Function:

...
DECLARE @beginDate DATETIME
DECLARE @endDate   DATETIME
DECLARE @return    DATETIME

SET @beginDate = '2000-01-01 00:00:00' 
-- Gets current Datetime
SET @endDate   = GETDATE() 

-- Days difference in the range
-- Using RAND again, generate a random date in the range
DECLARE @days   INT = DATEDIFF(DAY, @beginDate, @endDate)
DECLARE @random INT = ROUND(((@days - 1) * RAND()), 0)

SET @return = DATEADD(DAY, @random, @endDate)

RETURN(@return)

You can simply use NEWID() and GETDATE() functions for that and convert to the desired format afterwards:

DECLARE @myID uniqueidentifier = NEWID();
DECLARE @myDate datetime = GETDATE();
SELECT @myID, @myDate;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM