Get random records invariant on same day - sql

I have the folowing SQL table:
Create table Post (
Id int primary key not null,
Title nvarchar (80) not null
)
I need to get 4 random rows from the table but they would always be the same for the same Day.
How can this be done?

In MS SQL Server, you can use RAND function with current day of the year as the seed
For a specified seed value, the result returned is always the same.
RAND(DATEPART(dayofyear, GETDATE()))

Related

insert range of values in sql

CREATE TABLE RECHARGE(
R_LVL VARCHAR(20) NOT NULL PRIMARY KEY,
AMOUNT NUMBER,
POINTS_1 NUMBER
);
insert into RECHARGE
VALUES ('S1',(2950-4950),250);
i have the code above, and im trying to insert a range for the values in attribute amount, like this :
s1 : 2950-4950
s2: 5000-9950
s3: 10000-30000
so each lvl has it's own range of data, is it possible ?
Number datatype cannot store special characters like -. You have to make it either VARCHAR or store 2 rows with single number like -
insert into RECHARGE
VALUES ('S1',2950,250);
insert into RECHARGE
VALUES ('S1',4950,250);
Or you can use 2 colums also like FROM-TO to show your date range like -
CREATE TABLE RECHARGE(
R_LVL VARCHAR(20) NOT NULL PRIMARY KEY,
AMOUNT_FROM NUMBER,
AMOUNT_TO NUMBER,
POINTS_1 NUMBER
);
insert into RECHARGE
VALUES ('S1',2950,4950,250);
Then in SELECT query you can generate the result like you want.
Range consists of 2 values, store it in 2 columns.
The expression (2950-4950) equals to -2000 (2950 minus 4950).
You should create two columns or have only just one of the boundaries of the ranges stored.
I suggest to store both values, because it is easier to query:
CREATE TABLE RECHARGE(
R_LVL VARCHAR(20) NOT NULL PRIMARY KEY,
LOWER_BOUNDARY NUMBER,
UPPER_BOUNDARY NUMBER,
POINTS_1 NUMBER
);
You need to decide if the boundaries are closed (<=, >=) or open (<, >).
So you can query them like this:
SELECT * FROM Recharge WHERE LOWER_BOUNDARY <= 2000 AND UPPER_BOUNDARY > 2000
Where 2000 is the value you are trying to find the range for.
You can make this thing more bulletproof by adding a few constraints:
CHECK constraint to make sure that LOWER_BOUNDARY is lower than
UPPER_BOUNDARY.
UNIQUE on LOWER_BOUNDARY to eliminate repetition
FOREIGN KEY to reference the UPPER_BOUNDARY from the previous range
for the current ones LOWER_BOUNDARY (boundaries are continuous)
it is possible
use the next query
insert into RECHARGE
VALUES ('S1',(2950-4950),250)
('S2',(5000-9950),250)
('S3',(10000-30000),250)
;

How can I update the value of a field in a table to be a random number that's unique most of the time?

I have a simple table:
CREATE TABLE [dbo].[Word] (
[WordId] INT IDENTITY (1, 1) NOT NULL,
[NameId] INT NOT NULL
PRIMARY KEY CLUSTERED ([WordId] ASC)
);
I have a unique index on NameId
I am trying to update this table and change one column to a random number:
UPDATE Word SET NameId = ROUND(RAND()*2147483647,0)
I realize there is a very very small chance this will not work but it's actually failing every time even though the table has only a very small number of rows the update always fails and says there's a duplicate.
Can anyone tell me what's happening here and also suggest a way to update this table so that there's no duplicate values of NameId created most of the time.
You are updating every NameId with same value, use WHERE statement to update only one row
EDIT: This should do the trick you are looking for, NewId() generates new id for each row
UPDATE Word SET NameId = abs(checksum(NewId()) % 2147483647)
How many rows do you have? It could be a case of the birthday paradox.
Have you tried doing this:
SELECT ROUND(RAND()*2147483647,0) FROM Word
Do the numbers really need to be pseudo-random? You could use row_number() to make them increment.

How do I get the current date in SQL when entering data to a microsoft database?

I am using Microsoft SQL Server and SQL Server Management Studio.
I have a column called dateApplied which has a constraint like this:
[dateApplied] >= getDate()
When I enter a row the date is automatically added the row.
My problem is when I use the SELECT function, the dateApplied column is automatically changed to the current date and time in which the SELECT statement is called.
How do I prevent this from happening?
Thanks
Peter
I suppose you're using a computed column, like:
create table t1
(
id int
, date_col as getdate()
)
Try a default constraint instead:
create table t1
(
id int
, date_col datetime constraint DF_T1_DateCol default getdate() not null
)
A computed column is calculated whenever you run a query. A default constraint is only generated when the row is first inserted.

How do I properly SELECT INTO #TempTable Multiple times to return a single resultset?

I'm trying to write a stored procedure for Crystal Reports by combining multiple queries into a single resultset (Crystal doesn't support multiple results in one report).
The result set I'm trying to get combines columns from both tables.
In the SP, I declare #temptable and the columns (because the two tables i'm querying have different columns).
DECLARE #TEMPNEWBILLING TABLE
(
ACCOUNT DECIMAL null,
CLIENT NVARCHAR null,
TIMESTAMP INT null,
BILLING DECIMAL null,
CALLKIND INT null,
HITK1 DECIMAL null,
HITK2 DECIMAL null,
HIDISC DECIMAL null,
HITALK DECIMAL null,
HIPTCH DECIMAL null,
HICONF DECIMAL null,
HIHOLD DECIMAL null,
PTCH DECIMAL null,
SUPERTIME DECIMAL null
)
I then SELECT from both tables INTO the temp table:
SELECT Account, Client, Timestamp, Billing, CallKind, HiTk1, HiTk2, HiDisc, HiTalk, HiPtch, HiConf, HiHold, Ptch
INTO TEMPNEWBILLING
FROM
mCallEnd
WHERE billing = cast(#BILLINGNUMBER as decimal)
AND Timestamp > #STARTITIME
AND Timestamp < #ENDITIME
AND CallKind in (0,1,2,3,4,16)
SELECT
Billing, SuperTime
INTO TEMPNEWBILLING
FROM
mClientMaint
WHERE billing = cast(#BILLINGNUMBER as decimal)
AND Timestamp > #STARTITIME
AND Timestamp < #ENDITIME
And finally, I just get all data from the temp table.
SELECT * FROM #TEMPNEWBILLING
Unfortunately, something is going wrong, as when I run the SP, I get an error that
There is already an object named 'TEMPNEWBILLING' in the database.
I've checked it out and it seems that the first query is running, but the error gets thrown at the second Select Into. I must be doing this wrong, as I get the same error if I use # tables or # tables (i.e. delcare the table vs. create the table).
Is the prospect of filling a temp table with the results of two queries simply not possible? Am I using the wrong tool for the job?
SELECT... INTO creates a new table.
You'll want to reverse it:
INSERT INTO #TEMPNEWBILLING
(Columns...)
SELECT (your select query here)
You'll want to declare the table (technically it's a table variable since you're using the # sign) as you did. Then use INSERT INTO... SELECT... for all of your inserts.
In your code, you are not using the variable table youe defined, instead you are trying to put the results into the same physical table. Try this instead:
INSERT INTO #TEMPNEWBILLING(Account, Client, Timestamp, Billing, CallKind, HiTk1, HiTk2, HiDisc, HiTalk, HiPtch, HiConf, HiHold, Ptch)
SELECT Account, Client, Timestamp, Billing, CallKind, HiTk1, HiTk2, HiDisc, HiTalk, HiPtch, HiConf, HiHold, Ptch
FROM
mCallEnd
WHERE billing = cast(#BILLINGNUMBER as decimal)
AND Timestamp > #STARTITIME
AND Timestamp < #ENDITIME
AND CallKind in (0,1,2,3,4,16)
INSERT INTO #TEMPNEWBILLING(Billing, SuperTime)
SELECT
Billing, SuperTime
FROM
mClientMaint
WHERE billing = cast(#BILLINGNUMBER as decimal)
AND Timestamp > #STARTITIME
AND Timestamp < #ENDITIME
You need to use INSERT once the table is already created. Also, you're using a table variable, so you need to include the # at the beginning of the name when referring to it. Since you're declaring the table variable at the start, both statements should actually be INSERT and not SELECT INTO.
SELECT INTO tries to create a new table. In your code you basically declare a table variable (which never gets used), then your first SELECT INTO creates a permanent table with the name TEMPNEWBILLING, then your second SELECT INTO tries to create a table with the same exact name - hence the error.

Generating Random ID's in Microsoft SQL Server

I want to create a table in sql server and fill it up with data (people's info) every person should have a unique ID different than the auto incremented ID's by sql server
For example i need the ID for the first person inserted like this: 2016xxxx
how to fix the 2016 and randomly generate the numbers after that to be filled instead of xxxx
should i use a regular expression ?
You can also create a computed column like below
CREATE TABLE tableName
(
PkAutoId INT PRIMARY KEY IDENTITY(1,1),
PersonUniqueNo AS (CAST(DATEPART(YEAR,GETDATE()) AS VARCHAR) + RIGHT(RIGHT(CAST(RAND() AS VARCHAR),4) + CAST(PkAutoId AS VARCHAR),4))
)
Computed Column "PersonUniqueNo" is 8 Digit Unique Number comprising of Current Year And Conceited value of Random number and Primary Key Id for 4 Length, Total length will be 8 as asked.
You could create a function that would get the next value for you and use that instead of an AUTO_INCREMENT field.
I wouldn't recommend it tho. You shouldn't format the data like that before inserting it. That sort of thing should be done on the way out, preferably by the front-end code. Or you can just write a query and create a view ...
However if you must do that here is the complete answer with the code:
Is there a way to insert an auto-incremental primary id with a prefix in mysql database?