我的代码如下 如何在TSQL选择
中为每一行的特定范围生成随机日期 Declare @id int;
Declare @randomDate;
Declare crs Cursor For
Select id from myTable
open crs
fetch next from crs into @id
while @@FETCH_STATUS=0
begin
SET @randomDate=''
--Generate randomdate @randomDate
update myTable set dateModified=@randomDate where id=@id;
fetch next from crs into @id
end
close crs
deallocate crs
答案 0 :(得分:0)
按照以下answer,
Update myTable
SET
dateModified = DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0)
您无需任何游标即可完成此操作。对于像这样的简单操作,Cursors are bad。
答案 1 :(得分:0)
您可以使用CTE生成有效日期并随机选择其中一个:
class PersonalDetailViewSet(viewsets.ModelViewSet):
queryset = PersonalDetail.objects.all()
serializer_class = PersonalDetailSerializer
def get_queryset(self):
return PersonalDetail.objects.filter(Q(user_id=self.request.user))
def perform_create(self, serializer):
serializer.save(user_id=self.request.user)
# Not delete icon, id, preview_title
答案 2 :(得分:0)
这将提供特定开始日期和结束日期之间的随机日期。 我出于性能原因引入了@gap变量,它从主查询中删除了DATEDIFF函数的成本。
DECLARE @start DATETIME = '20170101'
DECLARE @end DATETIME = '20170201'
DECLARE @gap INT = DATEDIFF(DD,@start,@end)
UPDATE mytable SET dateModified = DATEADD(DD,@gap*RAND(),@start)