programing

임의의 날짜로 행을 업데이트하는 방법

instargram 2023. 7. 11. 21:28
반응형

임의의 날짜로 행을 업데이트하는 방법

저는 DateTime 열이 있는 간단한 SQL 테이블을 가지고 있습니다.모든 행(>100000 행)을 임의의 날짜로 업데이트하고 싶습니다.SQL 쿼리를 수행하는 간단한 방법이 있습니까?

1900년 1월 1일에서 2079년 6월 6일 사이의 작은 날짜를 생성하는 데 사용합니다(선택하지 않음, SQL이 설치되지 않음).

DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0)

NEWID는 랜드를 사용하는 것보다 낫습니다. 랜드는 단일 SELECT 또는 UPDATE에서 다른 값 행을 생성하지 않습니다(동작이 변경된 경우 SQL 2000에서는 생성되지 않았습니다).

편집: 이렇게

UPDATE
  table
SET
  datetimecol = DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0)

편집: 65535를 65530으로 변경하고 범위 상한에서 오버플로를 방지하기 위해 ABS를 추가했습니다.

아래 답변을 보완하겠습니다.

SELECT DATEADD(DAY, ABS(CHECKSUM(NEWID()) % 3650), '2000-01-01')
FROM your_table

이것은 2000-01-01부터 시작하는 날짜를 생성하며, 계수 값에서 일 수를 변경할 수 있습니다. 3650(약 10년)을 넣었습니다. 이 접근 방식은 오버플로우되지 않습니다.

업데이트를 원하는 경우

UPDATE your_table
SET your_date_field = DATEADD(DAY, ABS(CHECKSUM(NEWID()) % 3650), '2000-01-01')
WHERE your_conditions

이 질문은 꽤 오래된 것 같지만, 제 대답은 다른 사람들에게 유용할 수도 있습니다.

      Update table
      SET Time= DateAdd(d, ROUND(DateDiff(d, '2010-01-01', '2013-12-31') * RAND(CHECKSUM(NEWID())), 0),
      DATEADD(second,CHECKSUM(NEWID())%48000, '2010-01-01'))

그러면 지정된 범위 사이의 임의 날짜 시간이 생성됩니다.

저는 위의 Jonny의 답변을 과거 10년의 날짜로 수정했습니다.

SELECT dateadd(day, (abs(CHECKSUM(newid())) % 3650) * -1, getdate())

SQL Server 전용입니다.

1940년에서 1985년 사이에 제 모든 테스트 데이터에 대한 생년월일을 설정하기 위해 사용했습니다.

SET [Birth Date] = DATEADD(day, (ABS(CHECKSUM(NEWID())) % 16250), '1940-1-1 00:00:00.001')

다음 코드는 회계 연도 표의 시작 날짜 열을 지정된 두 날짜 사이의 임의 날짜로 채웁니다.

-- First, let's declare the date range.
DECLARE @date_from DATETIME;
DECLARE @date_to DATETIME;

-- Set the start and date dates. In this case, we are using
-- the month of october, 2006.
SET @date_from = '1985-10-14';
SET @date_to = '2009-04-27';

UPDATE FiscalYear SET StartDate =  
(
    -- Remember, we want to add a random number to the
    -- start date. In SQL we can add days (as integers)
    -- to a date to increase the actually date/time
    -- object value.
    @date_from +
    (
        -- This will force our random number to be >= 0.
        ABS
        (
            -- This will give us a HUGE random number that
            -- might be negative or positive.
            CAST(CAST(NewID() AS BINARY(8)) AS INT)
        )

        -- Our random number might be HUGE. We can't have
        -- exceed the date range that we are given.
        -- Therefore, we have to take the modulus of the
        -- date range difference. This will give us between
        -- zero and one less than the date range.
        %

        -- To get the number of days in the date range, we
        -- can simply substrate the start date from the
        -- end date. At this point though, we have to cast
        -- to INT as SQL will not make any automatic
        -- conversions for us.
        CAST((@date_to - @date_from) AS INT)
    )
)

저는 무작위 시간을 생성하는 이와 유사한 질문을 찾다가 이 스크립트를 찾았습니다.여기서 유용할 것이라고 생각했습니다.

DECLARE @DateFrom DATETime = '2001-01-01'
DECLARE @DateTo DATeTime = '2013-11-30'
DECLARE @DaysRandom Int= 0
DECLARE @MillisRandom Int=0

--get random number of days

select @DaysRandom= DATEDIFF(day,@DateFrom,@DateTo)
SELECT @DaysRandom = ROUND(((@DaysRandom -1) * RAND()), 0)

--get random millis
SELECT @MillisRandom = ROUND(((99999999) * RAND()), 0)

SELECT @DateTo = DATEADD(day, @DaysRandom, @DateFrom)
SELECT @DateTo = DATEADD(MILLISECOND, @MillisRandom, @DateTo)
SELECT @DateTo

저는 여기서 그것을 얻었습니다:

아래 코드를 사용하면 @Min(1)에서 @Max(365) 사이의 임의의 정수를 얻을 수 있으며, date add 기능을 사용하면 작년에 임의의 날짜를 만들 수 있습니다.

CREATE VIEW vRandNumber
AS
SELECT RAND() as RandNumber
GO

CREATE FUNCTION RandNumber(@Min int, @Max int)
RETURNS int
AS
 BEGIN
 RETURN round(@Min + (select RandNumber from vRandNumber) * (@Max-@Min),0)
 END
GO

Update table1
set theDate = dateadd(d,0-dbo.RandNumber(1,365),getdate())

임의의 숫자(양 또는 음)를 얻은 다음 해당 숫자를 날짜(시스템 날짜 변경)에 추가할 수 있습니다.

예를 들어 (지금은 sqlserver에 액세스할 수 없어서 구문을 확인할 수 없습니다.)

DATEADD(day, DATEDIFF(day, 0, GETDATE()) - 1 - FLOOR(RAND(CAST(NEWID() AS binary(4))) * 365.25 * 90), 0)

저는 제 자신을 위해 몇 가지 답을 조합했습니다, 당신에게 효과가 있다고 생각합니다.140k 행에 대해 이것을 실행하는 데 40초가 걸렸습니다. i5, 1333MHZ, standart laptop hdd

 DECLARE @rank INT = 0;

WHILE @rank < yourmaxrow --(you can use Select count (*) from your table name as well)
BEGIN
   DECLARE @FromDate DATETIME = DATEADD(DAY, -720, GETDATE()) -- 2 years back
   DECLARE @ToDate   DATETIME = DATEADD(DAY, -1, GETDATE()) -- until yesterday

   DECLARE @Seconds INT = DATEDIFF(SECOND, @FromDate, @ToDate)
   DECLARE @Random INT = ROUND(((@Seconds-1) * RAND()), 0)
   DECLARE @Milliseconds INT = ROUND((999 * RAND()), 0)

update yourtablename
Set yourdatetiemcolumnname = DATEADD(MILLISECOND, @Milliseconds, DATEADD(SECOND, @Random, @FromDate))
WHERE Id = @rank
   SET @rank = @rank + 1;       
END;

언급URL : https://stackoverflow.com/questions/794637/how-to-update-rows-with-a-random-date

반응형