Inputting Random Numbers To Table Column From Web Form
Feb 28, 2007
I'm grappling with this issue which I thought was basic VB programming; I'm trying to insert a random number (between 100 and 999) into a SQL table column (=Status_ID). This is input as part of a user submitting helpdesk requests via a APS.Net Web Form. The 'Status_ID' field is obviously not visible to the user but will help reference this Helpdesk request on the database.
Here is the code:
Protected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitButton.Click
If Page.IsValid Then
' Define data objects
Dim conn As SqlConnection
Dim comm As SqlCommand
' Read the connection string from web.config
Dim connectionString As String = _
ConfigurationManager.ConnectionStrings("ITNet_Students").ConnectionString
' Initialize connection
conn = New SqlConnection(connectionString)
' Create command
comm = New SqlCommand( _
"INSERT INTO HelpDesk (First_Name, Last_Name, StudentID, PersonalEmail," & _
"CategoryID, SubjectID, Description, StatusID) " & _
"VALUES (@First_Name, @Last_Name, @StudentID, @PersonalEmail, " & _
"@CategoryID, @SubjectID, @Description, @StatusID)", conn)
' Use randomize
Randomize()
Dim randomvalue As Integer
' Generate random value between 999 and 100.
randomvalue = Int((900 * Rnd()) + 100)
' Add command parameters
comm.Parameters.Add("@First_Name", System.Data.SqlDbType.NVarChar, 50)
comm.Parameters("@First_Name").Value = fnameTextBox.Text
.
.
.
comm.Parameters.Add("@StatusID", System.Data.SqlDbType.Int)
comm.Parameters("@StatusID").Value = randomvalue
'Enclose database code in Try-Catch-Finally
Try
' Open connection
conn.Open()
' Execute the command
comm.ExecuteNonQuery()
' Reload page if the query executed successfully
Response.Redirect("HelpDesk.aspx")
Catch
' Display error message
dbErrorMessage.Text = _
"Error submitting the help desk request! Please try again later, and/or change the entered data!"
Finally
'close connection
conn.Close()
End Try
End If
End Sub
----------------------------------------------------------------------------------------------------------------------
I keep getting the error message under 'Catch' and the page 'HelpDesk.aspx' is not reloading; the 'comm.ExecuteNonQuery()' is not executing.
Can anyone spot any inconsistencies in the declaration of the 'randomvalue' variable?
P.S: this code works fine if you replace 'randomvalue' with any integer in 'comm.Parameters("@StatusID").Value = randomvalue'
I have a table with a column ID of ContentID. The ID in that column is all NULLs. I need a way to change those nulls to a number. It does not matter what type of number it is as long as they are different. Can someone point me somewhere with a piece of T-SQL that I could use to do that. There are over 24000 rows so cursor change will not be very efficient.
I am trying to get random numbers to have a unique value for different processes, then I can identify each process. What happens is that I use rand() function without seed, so I got my random numbers, but after shutting down SQLServer and try to get again another random number after booting up, the same series of random numbers is given again and again. So if anyone knows how I can get unique values,even though reseting the server, and using random function or any other method which automatically provides unique values,I'll really appreciate it if you let me know it.
I have a table with a field called "host" and I want to replace the value of this column in each row with 'Host' followed by a random number. I have created the below function to do this: DECLARE @Random varchar; SELECT @Random = CONVERT(int, (20+1)*RAND())+ 1; UPDATE AnalogLines Set [Host Name] = 'Host' + @Random
This sorta works... the problem is, the random number is determine and then the SAME random number is applied to each row. I need a different random number for every row. Any ideas?
Hi there... I've got an interesting one, that I can't seem to get my head around. Maybe some legend out there might be able to give me a hand...
I'm looking for a way to produce a weighted set of random numbers. I'm doing some work for a client at the moment, and they want to issue 3 random "reward cards" to their members at certain times. These are a bit like discount vouchers etc. The problem is some cards have need to have a higher frequency than the others. I guess a similar problem to baseball cards, you buy a pack of cards, you get mostly common cards, but every now and then, you get a rare card.
Here is the table setup: CREATE TABLE [dbo].[Cards]( [CardID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Cards_CardID] DEFAULT (newid()), [CardName] [nvarchar](50) NOT NULL, [InsertRatio] [float] NULL, CONSTRAINT [PK_Cards] PRIMARY KEY CLUSTERED ( [CardID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 1', NULL) /* Null implies the card is a common card */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 2', NULL) /* Null implies the card is a common card */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 3', NULL) /* Null implies the card is a common card */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 4', NULL) /* Null implies the card is a common card */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 5', NULL) /* Null implies the card is a common card */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 6', NULL) /* Null implies the card is a common card */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 7', NULL) /* Null implies the card is a common card */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 8', NULL) /* Null implies the card is a common card */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Common 9', NULL) /* Null implies the card is a common card */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Rare 1', 0.02) /* 1:50 ratio */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Rare 2', 0.02) /* 1:50 ratio */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Rare 3', 0.02) /* 1:50 ratio */ INSERT INTO [dbo].[Cards]([CardName],[InsertRatio]) VALUES('Very Rare 1', 0.005) /* 1:200 ratio */
So what I need to do, is have a Stored Proc that I can execute and it returns back 3 random rows. Now in that single run, a card can't be duplicated.
Notice the Insert Ratio column? This has the ratio of the probability, eg a 1:50 insert ratio is equal to 0.02. For the common cards, a NULL value indicates it is a common.
Eventually, this table would have about 1000 rows in it, and about 200 of those would have various ratios (eg 1:50, 1:200, 1:1000, 1:8000 etc)
I have a report with a column which contains either a string such as "N/A" or a number such as 12. A user exports the report to Excel. In Excel the numbers are formatted as text.
I already tried to set the value as CDbl which returns error for the cells containing a string.
The requirement is to export the column to Excel with the numbers formatted as numbers and the strings such as "N/A' in the same column as string.
I'm trying to take data from a form and insert it into a SQL database. Everything works fine until I try inserting a number with the comma separator in the number field. The data type in SQL is integer. Are there any special settings to get SQL to accept a comma separated number using ASP?
Consider the below code: I am trying to find a way so that my select statement (which will actually be used to insert records) can randomly place values in the Source and Type columns that it selects from a list which in this case is records in a table variable. I dont really want to perform the insert inside a loop since the production version will work with millions of records. Anyone have any suggestions of how to change the subqueries that constitute these columns so that they are randomized?
SET NOCOUNT ON
Declare @RandomRecordCount as int, @Counter as int Select @RandomRecordCount = 1000
Declare @Type table (Name nvarchar(200) NOT NULL) Declare @Source table (Name nvarchar(200) NOT NULL) Declare @Users table (Name nvarchar(200) NOT NULL) Declare @NumericBase table (Number int not null)
Set @Counter = 0
while @Counter < @RandomRecordCount begin Insert into @NumericBase(Number)Values(@Counter) set @Counter = @Counter + 1 end
Insert into @Type(Name) Select 'Type: Buick' UNION ALL Select 'Type: Cadillac' UNION ALL Select 'Type: Chevrolet' UNION ALL Select 'Type: GMC'
Insert into @Source(Name) Select 'Source: Japan' UNION ALL Select 'Source: China' UNION ALL Select 'Source: Spain' UNION ALL Select 'Source: India' UNION ALL Select 'Source: USA'
Insert into @Users(Name) Select 'keith' UNION ALL Select 'kevin' UNION ALL Select 'chris' UNION ALL Select 'chad' UNION ALL Select 'brian'
select 1 ProviderId, -- static value '' Identifier, '' ClassificationCode, (select TOP 1 Name from @Source order by newid()) Source, (select TOP 1 Name from @Type order by newid()) Type
I have a table of id numbers that I wish to mask. My thought was to create a new column for this new id number and populate it with a unique sequential value - start at 1 and go as high as needed. My problem is that I cannot recall how to populate that column with a number...
One more question about this Custom Calendar table I'm creating. I have a column called "IsWorkdays" which indicates if the day represented by a row is a workday or not. For our purposes, I also need to create a row that accumulates those numbers by month. So, if it is the 3rd workday of the month, this column would have a 3. This is beyond my current T-SQL ability. Does anyone know how to do this?
I have a little question. I have an application which interfaces with a SQL Express Database. On a form, I want to bind a control which is made of several Radio buttons to a table column which is in fact a varchar(1). This is the picture:
Table column: OptVisualRpt varchar(1)
Screen control: 2 radio buttons
rb_VisRPTbImp_O for "yes"
rb_VisRPTbImp_N for "no"
I'm really scratching my head as how I can bind a single table column to my radio buttons controls. I think that I just can't this way but rather have to use an intermediate variable or control.
Solution 1?
I thought of using a local variable that I would set to "y" or "n" following "CheckedChanged" events fired from radio buttons but I don't know how to bind this variable to my table column.
Solution 2?
I thought of placing a hidden text control into my form, which one would be binded to my table column, that I would also set to "y" or "n" following "CheckedChanged" events fired from radio buttons.
Any of these solutions which would be feasible or any more neat way to do it?
i have a view joining 4 tables, i want the user to be able to input new records into the view and this to update the corresponding tables. is this possible???
However, each table will be linked to a seperate form (using vb). This means after each form the user will have inputted this data....i only want it to save into the view if information is inputted for all four tables. ie. if they input information only for two tables then do not add. All info is required... (i have been using a disconnected recordset)
I am trying to create a whole number DAX calculated column that is derived from a date column. Basically it gets the date from the source data column and outputs it as an integer in the YYYYMMDD format.So 01/OCT/2015 would become --> 20151001...I've been fidgeting with DAX but my problem is that I keep missing the leading zeroes for months and days. So 01/March/2015 becomes 201531 which is not what I want (I need 20150301 in this case).
I have a query that is exhibiting a strange behaviour on different databases.
I've got something like this ...
select a.col, ... from tab1 as a inner join ... union select a.col, ... from tab1 as a inner join ... order by col
I know how to fix the problem, I make the last line read "order by a.col" ... that is understood.
However, on some databases I get an error and on others I don't. All databases are on the same server instance which is sql server 2005 developer (developer version isn't relevant as it happens on customer machines too).
I'm just wondering if anyone has any ideas why it is 'random'. It's as though the statement is being compiled differently on different databases ... what is influencing that ?
I'm fishing for a way to create a workaround, so if anyone has any ideas it might push me down the road of understanding why.
The real code is way too big to include here and it's not really relevant.
As a clue to what I'm looking for, if I copy the database to another database using SSIS, the resultant database doesn't cause the error despite being logically the same.
Presumably it is some physical or security difference that is causing the error to occur.
I try to set up a testing sample table which contain one integer project_ID field for table Sample around 500 records, and want the project_ID to be random number within 1 to 99, how to implement script todo it? thanks!
I have a matrix report...the column results are as follows
Con Std , Con Access, SF Std, SF Acc, Broadband, Pay TV
how would i make the columns appear in the above order when displaying as it is default alphetically sorted...I have tried putting numbers at the front which work till I get to the number 10 which alphetically sorted is next to 1 not 9? is there a better way off sorting matrix column which have no specific criteria to sort from?
Hi,I need to extract randomly 5 records from the table "Questions". Now I useSELECT TOP 5 FROM Questions ORDERBY NEWID()And it works. The problem is that I need an additional thing: if SQLextracts record with ID=4, then it should not extract record with ID=9,because they are similar. I mean, I'd like something to tell SQL that if itextracts some questions, then it SHOULD NOT extract other ones.How can I do it?Thanks!Luke
I'm trying to join two columns together to form a new column
My code is basically in the form of can't post the actual since it would be cheating--school assignment
SELECT Column1Name,Column2Name, Column3Name,Column4Name, Column1Name+Column2Name AS NewColumn1 Column3Name+Column4Name AS NewColumn1 FROM OriginalTable
I'm trying to find a decent way of multiplying a set of numbers in a column without using a cursor in T-SQL.
There is no 'Product' aggregate function that I'm aware of in SQL 7 or 2000. The workaround I'm currently using is this :
SELECT EXP(SUM(LOG(ColumnName))) FROM tblName
This works fine, except when negative numbers are introduced. The LOG function does not allow negative numbers and therefore returns a domain error and the negative number is eliminated from the aggregate.
I could use a cursor to do the multiplication, however, this is proving too slow for the bulk calculations involved.
If anyone has any ideas or suggestions, then that would be much appreciated.
Insert INTO #EmployeeList('Cary zzz',null); Insert INTO #EmployeeList('01 Jack',null); Insert INTO #EmployeeList('02 Tommy',null); Insert INTO #EmployeeList('03 Ricardo',null); Insert INTO #EmployeeList('04 Jack',null); Insert INTO #EmployeeList('Les zzz',null); Insert INTO #EmployeeList('05 Tim',null);
The final data looks like this :
Cary zzz NULL 01 Jack NULL 02 Tommy NULL 03 Ricardo NULL 04 Jack NULL Les zzz NULL 05 Tim NULL
1. I want to delete all rows which have 'zzz' in it. 2. I want to remove the numbers from the empname column
Code Block Expected Output :
Jack NULL Tommy NULL Ricardo NULL Jack NULL Tim NULL
I have set up a 'Parameters' table that solely stores all pre-assigned selection values for a webform. I customized a stored query to Select the values from the Parameters table. I set up the webform. The result is that the form1.apsx automatically populates each DropDownList task with the pre-assigned values from the 'Parameters' table (for example, the stored values in the 'Parameters' table 'Home', 'Business', and 'Other' populate the drop down list for 'Type'). The programming to move the selected data from form1.aspx to a new table in the SQL database perplexes me. If possible, I would like to use the form1.aspx to Postback (or Insert) the "selected" data to a *new* column in a *new* table (such as writing the data to the 'CustomerType' column in the 'Customers' table; I clearly do not want to write back to the 'Parameters' table). Any help to get over this hurdle would be deeply appreciated.
I have a simple question to ask; I need to create a column with the data from my DOB column (which has the smalldatetime type attached to it). I know how to do that but I am not too sure how to convert the data from that column int normal character for example when I copy it into my newly created column and change the type to varchar I get this jan 16 1979 from this date 1979/01/16. But I actually want the data to look like this 19790116, so in effect I just want to take out the slashes.