Dynamically create table and insert data into the created table, I'm using following command to create a table dynamically and insert the values. I'm commented the sample value for the variable respectively.
Dim question, opt1, opt2, opt3, opt4, ans, paper As String
question = Request.QueryString("question") '<p>This is my first question</p>
opt1 = Request.QueryString("option1") ' option 1
opt2 = Request.QueryString("option2") ' option 2
opt3 = Request.QueryString("option3") ' option 3
opt4 = Request.QueryString("option4") ' option 4
ans = Request.QueryString("answer") ' 2
paper = Request.QueryString("paper") ' cs-5-cder-2012
'Response.Write("....")
Dim cs As String = ConfigurationManager.ConnectionStrings("eExamSolutionConnection").ConnectionString
Dim cn As New SqlConnection(cs)
Dim cmd As New SqlCommand
Dim cmdText As String
cmdText = "IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RAVI' AND TABLE_NAME = '" & paper & "') "
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " INSERT INTO " & paper & "(question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
cmdText = cmdText & " ELSE"
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " CREATE TABLE " & paper & "(question_Id int AUTO_INCREMENT,question varchar(MAX),option1 varchar(255),option2 varchar(255),option3 varchar(255),option4 varchar(255),answer varchar(2));"
cmdText = cmdText & " INSERT INTO " & paper & "(question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
Try
cmd.CommandText = cmdText.ToString
cmd.Connection = cn
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
cmd.Dispose()
cn.Dispose()
Response.Write("Question Added !!")
Catch ex As Exception
Response.Write(ex.ToString)
End Try
But, I'm getting exception
System.Data.SqlClient.SqlException: Incorrect syntax near '-'. Incorrect syntax near '-'. Incorrect syntax near '-'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String
methodName, Boolean async)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult
result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at ASP.admin_addquestion_aspx._Render_control1(HtmlTextWriter __w,
Control parameterContainer) in
D:\EWA\eExam\admin\addQuestion.aspx:line 40
Please use
Dim cmdText As String
cmdText = "IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RAVI' AND TABLE_NAME = '" & paper & "') "
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " INSERT INTO [" & paper & "](question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
cmdText = cmdText & " ELSE"
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " CREATE TABLE [" & paper & "](question_Id int IDENTITY(1,1),question varchar(MAX),option1 varchar(255),option2 varchar(255),option3 varchar(255),option4 varchar(255),answer varchar(2));"
cmdText = cmdText & " INSERT INTO [" & paper & "](question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
Instead of
Dim cmdText As String
cmdText = "IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RAVI' AND TABLE_NAME = '" & paper & "') "
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " INSERT INTO " & paper & "(question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
cmdText = cmdText & " ELSE"
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " CREATE TABLE " & paper & "(question_Id int AUTO_INCREMENT,question varchar(MAX),option1 varchar(255),option2 varchar(255),option3 varchar(255),option4 varchar(255),answer varchar(2));"
cmdText = cmdText & " INSERT INTO " & paper & "(question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
Problem was:
1 Table name should be[] at create and insert time.
2 For autoincremnet there will be IDENTITY(1,1) in SQL server.
You could try adding [ and ] around the table name, so it would become;
"IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RAVI' AND TABLE_NAME = ['" & paper & "']) "
Hyphen character "-" is not allowed in table name. You must replace it with either underscore "_" or completely remove it.
Related
I want to filter data by month and also year from sql database. I set my current date to (yyyy-MM-dd) format. From there i want to filter by month and year. Below is my source code.
Dim ServerDate As String
ServerDate = Date.Now.ToString("yyyy-MM-dd")
Dim nowYear As Integer
nowYear = Date.Now.Year
Dim nowMonth As Integer
nowMonth = Date.Now.Month
This one my select statement:
cmd.CommandText = "Select COUNT(*) FROM ScanningData WHERE ASSET_NUMBER=" & AssetTxt.Text & " And LOC_DEPT=" & DeptCodeTxt.Text & " AND UNIT_NO=" & UnitNoTxt.Text & " AND UPDATE_DATE='" & nowMonth & nowYear & "';"
Can someone help me on this. Thank you in advance
Use DATEPART
Eg(not tested for syntax error)
Select COUNT(*) FROM ScanningData
WHERE ASSET_NUMBER=" & AssetTxt.Text & " And LOC_DEPT=" & DeptCodeTxt.Text & "
AND UNIT_NO=" & UnitNoTxt.Text & " AND ( DATEPART(mm, CreationDate) = "& nowMonth & ") and (DATEPART(yy, CreationDate)="& nowYear & " )
So my code is going through the various components and creates bundles using the BuildKnittingRecords sub for the various components. My code works well when it creates the bundles for the Case "Sleeve", "Front", "Body", "Back" but when it gets to Case "Collar22-32" it gets stuck in the do until loop and as a result will keep on adding to PnlsToProduce(until it crashes cos the number is too big) instead of only running through the do until loop when it finds that component
Private Sub knittingdetailsheaderdataset()
bundlenum = 1
Dim SQL As String
Dim Adapter As New OleDbDataAdapter
Dim dt As New DataTable
Using con As New OleDbConnection(cnString)
Dim cmd As New OleDbCommand()
SQL = "Select bla bla
FROM bla bla
INNER Join bla bla"
(it's a very long sql statement, and not relevent to my issue)
cmd.Connection = con
cmd.CommandText = SQL
Adapter.SelectCommand = cmd
Adapter.Fill(dt)
For dr As Integer = 0 To dt.Rows.Count - 1
componentName = dt(dr)(6)
knittOrderID = dt(dr)(4)
componentID = dt(dr)(3)
sizeID = dt(dr)(5)
qtyppnl = dt(dr)(10)
Select Case componentName
Case "Sleeve", "Front", "Body", "Back"
MxBndleSz = 36
PnlsToProduce = dt(dr)(11)
BuildKnittingRecords(MxBndleSz, componentID, sizeID, PnlsToProduce, qtyppnl, knittOrderID, bundlenum)
Case "Collar22-32"
MxBndleSz = 200
PnlsToProduce = 0
Do Until componentName <> "Collar22-32" Or dr = dt.Rows.Count - 1
PnlsToProduce += dt(dr)(11)
Loop
Select Case PnlsToProduce
Case 50 To 100
PnlsToProduce = PnlsToProduce + 1
Case 101 To 250
PnlsToProduce = PnlsToProduce + 2
Case Is > 250
PnlsToProduce = PnlsToProduce + 3
End Select
BuildKnittingRecords(MxBndleSz, componentID, sizeID, PnlsToProduce, qtyppnl, knittOrderID, bundlenum)
End Select
Next
End Using
End Sub
Hence my question is, why is it doing this and how do I solve it?
This is my code for the BuildknittingRecord() sub, not sure if it's relevant in solving my issue:
Private Sub BuildKnittingRecords(ByRef MaxBundleSz As Integer, ByRef compID As Integer, ByRef sizeID As Integer, ByRef PnlsToproduce As Integer, ByRef QtyPerPanel As Integer, ByRef KnittingOrderID As Integer, ByRef bundlenum As Integer)
pnls2prod = PnlsToproduce
Dim cmdstring As String
Do Until pnls2prod < 10
If bundlenum < 10 Then
bundleNo = txtbatchno.Text & "-K0" & bundlenum
Else
bundleNo = txtbatchno.Text & "-K" & bundlenum
End If
bundlenum += 1
If pnls2prod <= MaxBundleSz Then
PanelsToMake = pnls2prod
cmdstring = " INSERT INTO [KN - KnittingDetailsHeader] (BatchNo, BundleNo, ComponentID, SizeID, PanelsToMake, QtyPerPanel, KnittingOrderID) VALUES('" & txtbatchno.Text & "', '" & bundleNo & "', " & compID & ", " & sizeID & ", " & PanelsToMake & ", " & QtyPerPanel & ", " & KnittingOrderID & ");"
Using con As New OleDbConnection(cnString)
Dim cmd As New OleDbCommand(cmdstring)
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.Connection.Open()
cmd.ExecuteNonQuery()
End Using
Exit Do
Else
If pnls2prod < 10 Then
PanelsToMake = pnls2prod + MaxBundleSz
cmdstring = " INSERT INTO [KN - KnittingDetailsHeader] (BatchNo, BundleNo, ComponentID, SizeID, PanelsToMake, QtyPerPanel, KnittingOrderID) VALUES('" & txtbatchno.Text & "', '" & bundleNo & "', " & compID & ", " & sizeID & ", " & PanelsToMake & ", " & QtyPerPanel & ", " & KnittingOrderID & ");"
Using con As New OleDbConnection(cnString)
Dim cmd As New OleDbCommand(cmdstring)
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.Connection.Open()
cmd.ExecuteNonQuery()
End Using
Exit Do
End If
PanelsToMake = MaxBundleSz
pnls2prod = pnls2prod - MaxBundleSz
cmdstring = " INSERT INTO [KN - KnittingDetailsHeader] (BatchNo, BundleNo, ComponentID, SizeID, PanelsToMake, QtyPerPanel, KnittingOrderID) VALUES('" & txtbatchno.Text & "', '" & bundleNo & "', " & compID & ", " & sizeID & ", " & PanelsToMake & ", " & QtyPerPanel & ", " & KnittingOrderID & ");"
Using con As New OleDbConnection(cnString)
Dim cmd As New OleDbCommand(cmdstring)
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.Connection.Open()
cmd.ExecuteNonQuery()
End Using
End If
Loop
End Sub
I have these two sql statements. But while executing,it show 'Syntax error in INSERT INTO statement.'
Dim sqlString As String
sqlString = "INSERT INTO CreditCardRecord(CustomerEmail, CardholderName,
CreditCardNo, CCExpMonth, CCExpYear, CVCNo, CardIssuingBank,
Amount) VALUES ('" & Master.cEmailDOnMasterPage & "','" &
cardholderName & "','" & creditCardNo & "','" & ccExpMonth & "',
'" & ccExpYesr & "','" & cvc & "','" & cardIssuingBank & "',
'" & totalamount & "')"
Dim sqlcommand As New OleDbCommand(sqlString, db)
sqlcommand.ExecuteNonQuery()
Dim customerRervation As String
customerRervation = "INSERT INTO CustomerReservation(CustomerEmail,
CustomerFN, CustomerLN, CustomerIdentityCard,
CustomerPhoneNo, Package, Table, Amount, BookingDate)
VALUSE ('" & Master.cEmailDOnMasterPage & "',
'" & customerFN & "','" & customerLN & "',
'" & customerIC & "','" & customerPhoneNo & "',
'" & lblShowPackage.Text & "','" & lblShowTable.Text &
"','" & totalamount & "','" & lblShowDate.Text & "')"
Dim sqlcommand2 As New OleDbCommand(customerRervation, db)
sqlcommand2.ExecuteNonQuery()
The issue in your 2nd sql query statement. You are wrongly spelled VALUES to VALUSE. so instead of VALUSE, use VALUES.
Dim customerRervation As String
customerRervation = "INSERT INTO CustomerReservation(CustomerEmail,
CustomerFN, CustomerLN, CustomerIdentityCard,
CustomerPhoneNo, Package, Table, Amount, BookingDate)
VALUES ('" & Master.cEmailDOnMasterPage & "',
'" & customerFN & "','" & customerLN & "',
'" & customerIC & "','" & customerPhoneNo & "',
'" & lblShowPackage.Text & "','" & lblShowTable.Text &
"','" & totalamount & "','" & lblShowDate.Text & "')"
Dim sqlcommand2 As New OleDbCommand(customerRervation, db)
sqlcommand2.ExecuteNonQuery()
Just add [] can already
Dim customerRervation As String
customerRervation = "INSERT INTO CustomerReservation([CustomerEmail],
[CustomerFN], [CustomerLN], [CustomerIdentityCard],
[CustomerPhoneNo], [Package], [Table], [Amount], [BookingDate])
VALUES ('" & Master.cEmailDOnMasterPage & "',
'" & customerFN & "','" & customerLN & "',
'" & customerIC & "','" & customerPhoneNo & "',
'" & lblShowPackage.Text & "','" & lblShowTable.Text &
"','" & totalamount & "','" & lblShowDate.Text & "')"
Dim sqlcommand2 As New OleDbCommand(customerRervation, db)
sqlcommand2.ExecuteNonQuery()
Im designing a website that allows a user to update a database with information. The problem I am having is that I have created various controls that are hidden when the page loads, but the user can click to unhide to add additional info.
The issue I am coming up against is writing the sql statement to handle identifying what controls are used. I have a viewstate count to let me know which panels are visible or not.
ViewState("count") = CInt(ViewState("count")) + 1
Label1.Text = ViewState("count").ToString()
And then the code behind to write the SQL query I have looks like this
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myConn As SqlConnection
Dim cmd As SqlCommand
Dim sqlstring As String
Dim dd As String
Dim mm As String
Dim yy As String
dd = Left(TextBox1.Text, 2)
mm = Mid(TextBox1.Text, 4, 2)
yy = Right(TextBox1.Text, 4)
myConn = New SqlConnection("xxx")
myConn.Open()
Select Case Label1.Text
Case Is = "0"
sqlstring = "INSERT INTO Transactions (Date, Account, Payee, Chq_Num, Reference, GST_Rate, Amount, Document_Number, Bank_Account) VALUES ('" & yy & "-" & mm & "-" & dd & "','" & DropDownList3.SelectedValue & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & TextBox4.Text & "'," & DropDownList2.SelectedValue & "," & TextBox6.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
Case Is = "1"
sqlstring = "INSERT INTO Transactions (Date, Account, Payee, Chq_Num, Reference, GST_Rate, Amount, Document_Number, Bank_Account) VALUES ('" & yy & "-" & mm & "-" & dd & "','" & DropDownList3.SelectedValue & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & TextBox4.Text & "'," & DropDownList2.SelectedValue & "," & TextBox6.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "') VALUES ('" & yy & "-" & mm & "-" & dd & "','" & DropDownList4.SelectedValue & "','" & TextBox7.Text & "','" & TextBox9.Text & "','" & TextBox8.Text & "'," & DropDownList5.SelectedValue & "," & TextBox10.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
End Select
cmd = New SqlCommand(sqlstring, myConn)
cmd.ExecuteNonQuery()
myConn.Close()
Response.Redirect(Request.RawUrl, True)
End Sub
My problem lies in the select case as when case is 1 it is only inserting the first values and not the second set. I have up to 6 "cases" to choose from, each time adding an additional set of values. Sql server is 2008
Any help is appreciated
I may be wrong but in the second statement the clause VALUES appears two two times.
That might be the source of your problem.
as above however you are going to end up with a horribly long string by the 6th case might want to re-engineer it to check >= each value if the previous strings are immutable
From SQL Server 2008 onwards, you can use the multi-values insert clause that looks like this
INSERT [INTO] tbl [(...columns...)]
VALUES (....),(....),(....);
You have constructed your query like this
INSERT [INTO] tbl [(...columns...)]
VALUES (....)
VALUES (....)
VALUES (....)
I would also personally have constructed the string concatenation not using a SELECT-CASE block:
If Label1.Text >= "0" Then
sqlstring = "('" & yy & "-" & mm & "-" & dd & "','" & DropDownList3.SelectedValue & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & TextBox4.Text & "'," & DropDownList2.SelectedValue & "," & TextBox6.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
End If
If Label1.Text >= "1" Then
sqlstring = sqlstring + "," + "('" & yy & "-" & mm & "-" & dd & "','" & DropDownList4.SelectedValue & "','" & TextBox7.Text & "','" & TextBox9.Text & "','" & TextBox8.Text & "'," & DropDownList5.SelectedValue & "," & TextBox10.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
End If
' etc
If for whatever arcane reason the multi-values statement doesn't work, you can always rely on the tried and true multi-statement batch, i.e.
If Label1.Text >= "0" Then
sqlstring = "INSERT ... VALUES (...);"
End If
If Label1.Text >= "1" Then
sqlstring = sqlstring + "INSERT ... VALUES (...);"
End If
If Label1.Text >= "2" Then
sqlstring = sqlstring + "INSERT ... VALUES (...);"
End If
' etc
Note the semicolon statement terminators within the batch.
The issue was not the select case but the viewstate not passing to the sql string correctly, I know possibly not the best solution but passed the label.text to a hidden textbox, which the sql string was able to read properly. Richard's suggestion to use a concatenated IF statement instead of Select Case was a great idea!
Thanks for all the help
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT [counts] FROM [a1_holds] WHERE (dates ='" & TextBox1.Text & "' BETWEEN from_date AND to_date) AND service ='" & lab5.Text & "' ORDER BY [id] ASC", SQLData)
ERROR :incorrect syntax near BETWEEN
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT [counts] FROM [a1_holds] WHERE ('" & TextBox1.Text & "' BETWEEN from_date AND to_date) AND service ='" & lab5.Text & "' ORDER BY [id] ASC", SQLData)
WHERE (dates = '...' BETWEEN ... AND ...)
is a syntax error. Either: ('...' BETWEEN ... AND ...) or (dates = '...')