date not being compared in sql server 2000 - sql-server

I have FrmDt and ToDt as datetime column in sql server2000. I am comparing dates in these columns with two datetimepicker like this-
SQL query :
SqlCmd = New SqlCommand("SELECT DISTINCT AllwnsDedId FROM vwGetEmpCntrctWisePaymnt
WHERE Type=1 AND Emp_ID='" & txtEmpID.Text & "'
AND FrmDt>='" & dtp1dtp1.Value.Date & "' AND ToDt<='" & dtp2dtp1.Value.Date & "'", Sqlconn)
In Query Analyzer, I tried :
FrmDt>='01/21/2015' AND ToDt<='01/21/2016'
Its giving me correct output. But I am not getting the output in Vb.net? Anything missing?

In order for this to work reliably you need to use proper Date datatypes. Change your SQL to something like;
WHERE FrmDt>=#FrmDt AND ToDt<=#ToDt
then add 2 paramater objects to the command, one for each date. Your code should end up something like this;
SqlCmd = New SqlCommand("SELECT DISTINCT AllwnsDedId FROM vwGetEmpCntrctWisePaymnt
WHERE Type=1 AND Emp_ID='" & txtEmpID.Text & "'
AND FrmDt>=#FrmDt AND ToDt<=#ToDt", Sqlconn)
SqlCmd.Parameters.Add("#FrmDt", SqlDbType.DateTime).Value = dtp1dtp1.Value.Date
SqlCmd.Parameters.Add("#ToDt", SqlDbType.DateTime).Value = dtp2dtp1.Value.Date

Related

Sql Update command VB.Net With Date

I have an SQL update command that I can't get to work. i want it to update the fields where the date is equal to the current date. It works for my INSERT and SELECT statements. But I get a missing operator error when using it for my Delete statement below.
Cmd.Connection = conn
Cmd.CommandText = "UPDATE tbl_Expenditure SET E_Stock =" & NewEStock & "," & "E_Total =" & ETotal & "WHERE [E_Date] = #" & thisMonth & "/" & Day & "/" & thisYear & "#;"
Cmd.ExecuteNonQuery()
Ive tried searching this site as well as others and can't seem to find an answer.
This is my error
Syntax error (missing operator) in query expression '95WHERE [E_Date] = #4/1/2015#'.
Thanks for any help
Using conn As New SqlConnection("connection string here"), _
cmd As New SqlCommand("UPDATE tbl_Expenditure SET E_Stock = #Stock, E_Total = #Total WHERE [E_Date] = #Date;", conn)
'Guessing at column types here
cmd.Parameters.Add("#Stock", SqlDbType.Int).Value = NewEStock
cmd.Parameters.Add("#Total", SqlDbType.Decimal, 8, 2).Value = ETotal
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = New DateTime(thisYear, thisMonth, Day)
cmd.ExecuteNonQuery()
End Using
This fixes a HUGE security issue in the code, it has a performance benefit in allowing Sql Server to cache your query plan, and it solves your problem in that is makes it much easier to spot silly syntax mistakes like the missing space in front of the WHERE clause.

The SQL statement works properly in SQL Server database, but errors in vb.net

I need to insert new record into a SQL Server database, but get
Incorrect syntax error
The strange thing is when I try to query the same statement in SQL Server itself, it works properly.
The code in vb.net is as follows:
insertSql = "INSERT INTO Seg_LINE VALUES (" & OBJECTID & ", 'test" + "', '" + "test" + "','" + DrainName + "'," & UID & ")"
logger.Info("insert sql = " + insertSql)
Dim cmdInsert As New SqlClient.SqlCommand(insertSql, Sqlconnection)
cmdInsert.ExecuteNonQuery()
The OBJECTID and UID are number parameters.
I cannot figure out what's wrong with my code, I am using vb.net(vs2102).
Most likely you have a DrainName value with a single quote in it. You're lucky the query is just failing, and not executing unwanted commands on your DB server. Don't use string concatenation like that to build queries! You need to use query parameters, like this:
insertSql = "INSERT INTO Seg_LINE VALUES (#ObjectID, 'test', 'test', #DrainName, #UID)"
logger.Info("insert sql = " + insertSql)
Dim cmdInsert As New SqlClient.SqlCommand(insertSql, Sqlconnection)
'I'm guessing at these parameter types. Use the actual db types of the columns
cmdInsert.Parameters.Add("#ObjectID", SqlDbType.Int).Value = OBJECTID
cmdInsert.Parameters.Add("#DrainName", SqlDbType.NChar, 50).Value = DrainName
cmdInsert.Parameters.Add("#UID", SqlDbType.Int).Value = UID
cmdInsert.ExecuteNonQuery()
Changing the code this way will also likely fix your syntax error.

ASP Classic, getting just the data from datetime from a database query

Ive looked around Google and can't find any working code. I want to query my database to return just results from a certain date. But the datetime column in my database has both the Date and the Time.
How would I go about doing this.
today = 15/08/2013
An example of one of the database values = 15/08/2013 02:13:18 PM
And here is my code at the moment
'Connect to database
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.ACE.OLEDB.12.0"
conn.Open Server.MapPath("/nightclub_photography/data/database/jamsnaps.mdb")
'Get the current date
today = Request.Cookies("sdate")
response.write today
sql = "SELECT * FROM sales WHERE saleDate =" & today
Set rs = conn.Execute(sql)
if rs.EOF then
response.write "Error!"
end if
Dates are passed as strings. Wrap them in single quotes.
sql = "SELECT * FROM sales WHERE saleDate = '" & today & "'"
Hmm, I used this in some other code which seemed to work.
DATEVALUE(columnName)
If you know that today consists of only the date, you could concatenate the time and do something like this:
sql = "SELECT * FROM sales WHERE saleDate >= '" & today & " 00:00:00' AND today <= '" & today & " 23:59:59'"
You could use one of VBScript's date functions to guarantee the contents of today are only the date if you want to be sure. Something like:
today = FormatDateTime(today,vbShortDate)

how to insert update and delete records in tables

I have a large windows form with 50 different fields (text boxes,combo boxes,listview,check box) i have 10 tables in sql server database each table have different column I want to insert my windows forms 50 fields in these 10 tables. Here is my code to insert record in a table
Dim cmd As New SqlCommand
cmd.Connection = conn
cmd.CommandText = "Insert Into ChartOfAccount (MainCode,MainDescription,AccountCode,AccountDescription,OpeningBalance) values ('" & MainCode & "','" & MainDescription & "','" & AccountCode & "','" & AccountDescription & "','" & OpeningBalance & "')"
cmd.ExecuteNonQuery()
So question is if I insert data into 10 different tables then I need to write 10 insert statments.
If I update or delete record I need to write update and delete command 10 tables seprately
this will take long time please guide me if any short method exists.
Your query is susceptible with SQL injection so better to use parameters:
Dim connStr as String = "connection string values here";
using con as new SqlConnection(connStr)
Dim commandText as String =
#"Insert Into ChartOfAccount (MainCode
,MainDescription,AccountCode
,AccountDescription,OpeningBalance)
VALUES
(#MainCode, #MainDesc,#AccountCode
,#AccountDesc,#OpeningBalance)"
Dim cmd as New SqlCommand(commandText,con)
cmd.Parameters.AddWithValue("#MainCode",MainCode)
cmd.Parameters.AddWithValue("#MainDesc",MainDescription)
cmd.Parameters.AddWithValue("#AccountCode",AccountCode)
cmd.Parameters.AddWithValue("#AccountDesc",AccountDescription)
cmd.Parameters.AddWithValue("#OpeningBalance",OpeningBalance)
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex as Exception
MessageBox.Show(ex.Message)
End Try
End Using
Now, this is only for Inserting records example.
You can create a stored procedure for that. In order to create a stored procedure, you can use the following SQL query:
Create procedure [dbo].[NewUser]
#Yourparameter1 int ,
#Yourparamtere2
As
Insert into dbo.Users
(
// Db columns
Column1 ,
Column2
)
values
(
#Yourparameter1
#Yourparameter2
)
And in your C# code, create a SQLParameter collection and pass it to the procedure. It will work fine and smoothly, and this way your code will be simpler.

VB.Net DataAdapter Select String

I have a routine to pull data from my database (nothing fancy). I want it to pull rows in which the "StartDate" column is some date in the future. The code below pulls all the rows instead of just the future ones.
I know it must be something silly that I'm doing but I can't figure it out.
Thanks in advance,
Craig
CODE:
Printda = New OleDbDataAdapter("SELECT * FROM tblShows WHERE StartDate > " & Format(Now, "Short Date"), cn)
Updated Code:
Printda = New OleDbDataAdapter("SELECT * FROM tblShows WHERE StartDate > '" & Now.ToString("Short Date") & "'", cn)
Corrected Code:
Printda = New OleDbDataAdapter("SELECT * FROM tblShows WHERE StartDate > Now()", cn)
Try this:
"SELECT * FROM tblShows WHERE StartDate > #" & Now.ToString("MM/dd/yyyy") & "#"
In SQL Server this is the default date format. In Oracle is YYYY-MM-DD. Use the format that fit your needs, or use parameters if you don't want to care about formatting and give your querys security.
Or you could simply use proper function to get the actual date:
"SELECT * FROM tblShows WHERE StartDate > now()"

Resources