Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Friday, March 30, 2012

Inserting a Decimal - HELP

Im trying to insert a decimal into SQL 2000 using a stored procedure. I can successfully insert it using a direct T-SQL statement inside the code, but I cant insert it correctly when calling for a stored procedure.

For instance 12.5 will insert as 12.

Here is my SQL Parameter code:
[code]
MyCommand.Parameters.Add(New SqlParameter("@.Num", SqlDbType.Decimal))
MyCommand.Parameters("@.Num").Precision = 5
MyCommand.Parameters("@.Num").Scale = 2
MyCommand.Parameters("@.Num").Value = Convert.ToDecimal(TextBox1.Text)
[/code]

I also declared @.Num to be a decimal in my Stored Procedure.

As you can see I give the Parameter more than enough detail about the data type as well as convert the textbox value to a decimal, but it still rounds the value to an integer like data.

Again using a direct T-SQL statement inside the code works OK, but the stored procedure will not.
ANyone got any ideas why this is happening.Try running Profiler and tracing the transaction. Then you can determine if the precision is being lost when .NET sends the command to SQL Server, or when SQL Server calls the stored procedure. Have you tried not being so specific? Can you post the source code for your stored procedure?


MyCommand.Parameters.Add("@.Num", Convert.ToDecimal(TextBox1.Text))

Inserting a dataset into an sql table

I've cleaned up and parsed a delimited file into a dataset.
Now I want to add that dataset to an sql table.
Simple, right?
My code is below.
It runs, but no records from the parsed file are added to the table.
Can anyone look at this code and make it work?
Thanks
Paul
PS Bulk Insert is a nice idea, and if anyone knows how to use it to insert
my dataset, I'm all ears.
========================================
=========
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
namespace Bot_01
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.DataGrid dataGrid1;
private System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1;
private System.Data.SqlClient.SqlCommand sqlSelectCommand1;
private System.Data.SqlClient.SqlCommand sqlInsertCommand1;
private System.Data.SqlClient.SqlCommand sqlUpdateCommand1;
private System.Data.SqlClient.SqlCommand sqlDeleteCommand1;
private System.Data.SqlClient.SqlConnection sqlConnection1;
private Bot_01.DataSet1 dataSet11;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.dataGrid1 = new System.Windows.Forms.DataGrid();
this.sqlDataAdapter1 = new System.Data.SqlClient.SqlDataAdapter();
this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlInsertCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlUpdateCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlDeleteCommand1 = new System.Data.SqlClient.SqlCommand();
this.sqlConnection1 = new System.Data.SqlClient.SqlConnection();
this.dataSet11 = new Bot_01.DataSet1();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dataSet11)).BeginInit();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(0, 0);
this.button1.Name = "button1";
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(88, 8);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(200, 256);
this.dataGrid1.TabIndex = 1;
//
// sqlDataAdapter1
//
this.sqlDataAdapter1.DeleteCommand = this.sqlDeleteCommand1;
this.sqlDataAdapter1.InsertCommand = this.sqlInsertCommand1;
this.sqlDataAdapter1.SelectCommand = this.sqlSelectCommand1;
this.sqlDataAdapter1.TableMappings.AddRange(new
System.Data.Common.DataTableMapping[] {
new System.Data.Common.DataTableMapping("Table",
"SEC_Index_01", new System.Data.Common.DataColumnMapping[] {
new
System.Data.Common.DataColumnMapping("CompanyName", "CompanyName"),
new
System.Data.Common.DataColumnMapping("FormType", "FormType"),
new
System.Data.Common.DataColumnMapping("CIK", "CIK"),
new
System.Data.Common.DataColumnMapping("DateFiled", "DateFiled"),
new
System.Data.Common.DataColumnMapping("SECWebAddress", "SECWebAddress")})});
this.sqlDataAdapter1.UpdateCommand = this.sqlUpdateCommand1;
//
// sqlSelectCommand1
//
this.sqlSelectCommand1.CommandText = "SELECT ID, CompanyName, FormType,
CIK, DateFiled, SECWebAddress FROM SEC_Index_01" +
"";
this.sqlSelectCommand1.Connection = this.sqlConnection1;
//
// sqlInsertCommand1
//
this.sqlInsertCommand1.CommandText = "INSERT INTO
SEC_Index_01(CompanyName, FormType, CIK, DateFiled, SECWebAddress) VA" +
"LUES (@.CompanyName, @.FormType, @.CIK, @.DateFiled, @.SECWebAddress);
SELECT ID, Com" +
"panyName, FormType, CIK, DateFiled, SECWebAddress FROM SEC_Index_01
WHERE (ID = " +
"@.@.IDENTITY)";
this.sqlInsertCommand1.Connection = this.sqlConnection1;
this.sqlInsertCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.CompanyName",
System.Data.SqlDbType.VarChar, 8000, "CompanyName"));
this.sqlInsertCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.FormType",
System.Data.SqlDbType.VarChar, 8000, "FormType"));
this.sqlInsertCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.CIK", System.Data.SqlDbType.VarChar,
8000, "CIK"));
this.sqlInsertCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.DateFiled",
System.Data.SqlDbType.VarChar, 8000, "DateFiled"));
this.sqlInsertCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.SECWebAddress",
System.Data.SqlDbType.VarChar, 8000, "SECWebAddress"));
//
// sqlUpdateCommand1
//
this.sqlUpdateCommand1.CommandText = @."UPDATE SEC_Index_01 SET
CompanyName = @.CompanyName, FormType = @.FormType, CIK = @.CIK, DateFiled =
@.DateFiled, SECWebAddress = @.SECWebAddress WHERE (ID = @.Original_ID) AND (CI
K
= @.Original_CIK OR @.Original_CIK IS NULL AND CIK IS NULL) AND (CompanyName =
@.Original_CompanyName OR @.Original_CompanyName IS NULL AND CompanyName IS
NULL) AND (DateFiled = @.Original_DateFiled OR @.Original_DateFiled IS NULL AN
D
DateFiled IS NULL) AND (FormType = @.Original_FormType OR @.Original_FormType
IS NULL AND FormType IS NULL) AND (SECWebAddress = @.Original_SECWebAddress O
R
@.Original_SECWebAddress IS NULL AND SECWebAddress IS NULL); SELECT ID,
CompanyName, FormType, CIK, DateFiled, SECWebAddress FROM SEC_Index_01 WHERE
(ID = @.ID)";
this.sqlUpdateCommand1.Connection = this.sqlConnection1;
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.CompanyName",
System.Data.SqlDbType.VarChar, 8000, "CompanyName"));
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.FormType",
System.Data.SqlDbType.VarChar, 8000, "FormType"));
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.CIK", System.Data.SqlDbType.VarChar,
8000, "CIK"));
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.DateFiled",
System.Data.SqlDbType.VarChar, 8000, "DateFiled"));
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.SECWebAddress",
System.Data.SqlDbType.VarChar, 8000, "SECWebAddress"));
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_ID", System.Data.SqlDbType.Int
,
4, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)),
((System.Byte)(0)), "ID", System.Data.DataRowVersion.Original, null));
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_CIK",
System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
false, ((System.Byte)(0)), ((System.Byte)(0)), "CIK",
System.Data.DataRowVersion.Original, null));
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_CompanyName",
System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
false, ((System.Byte)(0)), ((System.Byte)(0)), "CompanyName",
System.Data.DataRowVersion.Original, null));
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_DateFiled",
System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
false, ((System.Byte)(0)), ((System.Byte)(0)), "DateFiled",
System.Data.DataRowVersion.Original, null));
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_FormType",
System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
false, ((System.Byte)(0)), ((System.Byte)(0)), "FormType",
System.Data.DataRowVersion.Original, null));
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_SECWebAddress",
System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
false, ((System.Byte)(0)), ((System.Byte)(0)), "SECWebAddress",
System.Data.DataRowVersion.Original, null));
this.sqlUpdateCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.ID", System.Data.SqlDbType.Int, 4,
"ID"));
//
// sqlDeleteCommand1
//
this.sqlDeleteCommand1.CommandText = @."DELETE FROM SEC_Index_01 WHERE (ID
= @.Original_ID) AND (CIK = @.Original_CIK OR @.Original_CIK IS NULL AND CIK IS
NULL) AND (CompanyName = @.Original_CompanyName OR @.Original_CompanyName IS
NULL AND CompanyName IS NULL) AND (DateFiled = @.Original_DateFiled OR
@.Original_DateFiled IS NULL AND DateFiled IS NULL) AND (FormType =
@.Original_FormType OR @.Original_FormType IS NULL AND FormType IS NULL) AND
(SECWebAddress = @.Original_SECWebAddress OR @.Original_SECWebAddress IS NULL
AND SECWebAddress IS NULL)";
this.sqlDeleteCommand1.Connection = this.sqlConnection1;
this.sqlDeleteCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_ID", System.Data.SqlDbType.Int
,
4, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)),
((System.Byte)(0)), "ID", System.Data.DataRowVersion.Original, null));
this.sqlDeleteCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_CIK",
System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
false, ((System.Byte)(0)), ((System.Byte)(0)), "CIK",
System.Data.DataRowVersion.Original, null));
this.sqlDeleteCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_CompanyName",
System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
false, ((System.Byte)(0)), ((System.Byte)(0)), "CompanyName",
System.Data.DataRowVersion.Original, null));
this.sqlDeleteCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_DateFiled",
System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
false, ((System.Byte)(0)), ((System.Byte)(0)), "DateFiled",
System.Data.DataRowVersion.Original, null));
this.sqlDeleteCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_FormType",
System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
false, ((System.Byte)(0)), ((System.Byte)(0)), "FormType",
System.Data.DataRowVersion.Original, null));
this.sqlDeleteCommand1.Parameters.Add(new
System.Data.SqlClient.SqlParameter("@.Original_SECWebAddress",
System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
false, ((System.Byte)(0)), ((System.Byte)(0)), "SECWebAddress",
System.Data.DataRowVersion.Original, null));
//
// sqlConnection1
//
this.sqlConnection1.ConnectionString = "workstation id=AMD;packet
size=4096;integrated security=SSPI;data source=AMD;pers" +
"ist security info=False;initial catalog=SEC_XBRL_10";
//
// dataSet11
//
this.dataSet11.DataSetName = "DataSet1";
this.dataSet11.Locale = new System.Globalization.CultureInfo("en-US");
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.dataGrid1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataSet11)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
dataGrid1.DataSource=null; //Clear the
datagrid
sqlDataAdapter1.Fill(dataSet11,"SEC_Index_01"); //Fill result dataset
with SEC_Index_01 table data via the sqlDataAdapter1
//WebRequest req =
WebRequest.Create("http://www.sec.gov/Archives/edgar/daily-index/" +
"company." + "20041222" + ".idx"); // Create the Request object
//WebResponse response = req.GetResponse(); //Create the
Response object
//Stream stream = response.GetResponseStream(); //Create a
Stream
//StreamReader sr = new StreamReader(stream); //Open the file
in a stream reader
StreamReader sr = new StreamReader("C:\\test.txt"); //Read From
A File instead of a webrequest
dataSet11.Tables.Add("MyNewTable"); //Add DataTable to
hold the DataSet
dataSet11.Tables["MyNewTable"].Columns.Add("CompanyName"); //Add a
single column to the DataTable
dataSet11.Tables["MyNewTable"].Columns.Add("FormType"); //Add a
single column
dataSet11.Tables["MyNewTable"].Columns.Add("CIK"); //Add a
single column
dataSet11.Tables["MyNewTable"].Columns.Add("DateFiled"); //Add a
single column
dataSet11.Tables["MyNewTable"].Columns.Add("SECWebAddress"); //Add a
single column
string AllData1 = sr.ReadToEnd(); //Read the rest
of the data in the file.
string[] rows = AllData1.Split("\n".ToCharArray()); //Split off
each row at the Line Feed
foreach(string r in rows) //Now add each
row to the DataSet
{
string delimStr1 = "\t";
string[] items = r.Split(delimStr1.ToCharArray()); //Split the row
at the delimiter
dataSet11.Tables["MyNewTable"].Rows.Add(items); //Add the item
}
for (int i = 1; i <= 11; i++) //Remove first 11
rows from the DataTable/DataSet
{
dataSet11.Tables["MyNewTable"].Rows.RemoveAt(0);
}
sqlDataAdapter1.InsertCommand = sqlInsertCommand1; //Insert the new
rows from the "result" dataset
//sqlDataAdapter1.Update(dataSet11,"SEC_Index_01"); //Perform the
update
dataGrid1.SetDataBinding(dataSet11, "MyNewTable"); //Binds DataGrid to
DataSet,displaying datatable.
MessageBox.Show("Data has been added to the SQL Table SEC_XBRL_Index");
}
}
}Here's the reply to your earlier post...
A quick browse through your code, you have this line:
sqlDataAdapter1.Update(dataSet11,"SEC_Index_01"); //Perform the
update
which sends the updates (i.e. insert, update, delete operation) to sqlserver
for SEC_Index_01 table.
You have to addrow to dataSet11.Tables["SEC_Index_01"] if you want the
inserts!
The gist of it is you would want to add this to your code before calling
da.update.
e.g.
foreach(DataRow dr in dataSet11.Tables["MyNewTable"].Rows)
{
DataRow r = dataSet11.Tables["SEC_Index_01"].NewRow();
r["CompanyName"] = dr["CompanyName"];
// ... do the same for the rest of your columns
dataSet11.Tables["SEC_Index_01"].Rows.Add(r);
}
-oj
"a" <a@.discussions.microsoft.com> wrote in message
news:35A6293F-CA8B-415E-9DEE-36ECD43B5F3D@.microsoft.com...
> I've cleaned up and parsed a delimited file into a dataset.
> Now I want to add that dataset to an sql table.
> Simple, right?
> My code is below.
> It runs, but no records from the parsed file are added to the table.
> Can anyone look at this code and make it work?
> Thanks
> Paul
> PS Bulk Insert is a nice idea, and if anyone knows how to use it to insert
> my dataset, I'm all ears.
> ========================================
=========
> using System;
> using System.Drawing;
> using System.Collections;
> using System.ComponentModel;
> using System.Windows.Forms;
> using System.Data;
> using System.Data.SqlClient;
> using System.Net;
> using System.IO;
> using System.Text;
> using System.Text.RegularExpressions;
> using System.Collections.Specialized;
> namespace Bot_01
> {
> /// <summary>
> /// Summary description for Form1.
> /// </summary>
> public class Form1 : System.Windows.Forms.Form
> {
> private System.Windows.Forms.Button button1;
> private System.Windows.Forms.DataGrid dataGrid1;
> private System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1;
> private System.Data.SqlClient.SqlCommand sqlSelectCommand1;
> private System.Data.SqlClient.SqlCommand sqlInsertCommand1;
> private System.Data.SqlClient.SqlCommand sqlUpdateCommand1;
> private System.Data.SqlClient.SqlCommand sqlDeleteCommand1;
> private System.Data.SqlClient.SqlConnection sqlConnection1;
> private Bot_01.DataSet1 dataSet11;
> /// <summary>
> /// Required designer variable.
> /// </summary>
> private System.ComponentModel.Container components = null;
> public Form1()
> {
> //
> // Required for Windows Form Designer support
> //
> InitializeComponent();
> //
> // TODO: Add any constructor code after InitializeComponent call
> //
> }
> /// <summary>
> /// Clean up any resources being used.
> /// </summary>
> protected override void Dispose( bool disposing )
> {
> if( disposing )
> {
> if (components != null)
> {
> components.Dispose();
> }
> }
> base.Dispose( disposing );
> }
> #region Windows Form Designer generated code
> /// <summary>
> /// Required method for Designer support - do not modify
> /// the contents of this method with the code editor.
> /// </summary>
> private void InitializeComponent()
> {
> this.button1 = new System.Windows.Forms.Button();
> this.dataGrid1 = new System.Windows.Forms.DataGrid();
> this.sqlDataAdapter1 = new System.Data.SqlClient.SqlDataAdapter();
> this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
> this.sqlInsertCommand1 = new System.Data.SqlClient.SqlCommand();
> this.sqlUpdateCommand1 = new System.Data.SqlClient.SqlCommand();
> this.sqlDeleteCommand1 = new System.Data.SqlClient.SqlCommand();
> this.sqlConnection1 = new System.Data.SqlClient.SqlConnection();
> this.dataSet11 = new Bot_01.DataSet1();
> ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
> ((System.ComponentModel.ISupportInitialize)(this.dataSet11)).BeginInit();
> this.SuspendLayout();
> //
> // button1
> //
> this.button1.Location = new System.Drawing.Point(0, 0);
> this.button1.Name = "button1";
> this.button1.TabIndex = 0;
> this.button1.Text = "button1";
> this.button1.Click += new System.EventHandler(this.button1_Click);
> //
> // dataGrid1
> //
> this.dataGrid1.DataMember = "";
> this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
> this.dataGrid1.Location = new System.Drawing.Point(88, 8);
> this.dataGrid1.Name = "dataGrid1";
> this.dataGrid1.Size = new System.Drawing.Size(200, 256);
> this.dataGrid1.TabIndex = 1;
> //
> // sqlDataAdapter1
> //
> this.sqlDataAdapter1.DeleteCommand = this.sqlDeleteCommand1;
> this.sqlDataAdapter1.InsertCommand = this.sqlInsertCommand1;
> this.sqlDataAdapter1.SelectCommand = this.sqlSelectCommand1;
> this.sqlDataAdapter1.TableMappings.AddRange(new
> System.Data.Common.DataTableMapping[] {
> new System.Data.Common.DataTableMapping("Table",
> "SEC_Index_01", new System.Data.Common.DataColumnMapping[] {
> new
> System.Data.Common.DataColumnMapping("CompanyName", "CompanyName"),
> new
> System.Data.Common.DataColumnMapping("FormType", "FormType"),
> new
> System.Data.Common.DataColumnMapping("CIK", "CIK"),
> new
> System.Data.Common.DataColumnMapping("DateFiled", "DateFiled"),
> new
> System.Data.Common.DataColumnMapping("SECWebAddress",
> "SECWebAddress")})});
> this.sqlDataAdapter1.UpdateCommand = this.sqlUpdateCommand1;
> //
> // sqlSelectCommand1
> //
> this.sqlSelectCommand1.CommandText = "SELECT ID, CompanyName, FormType,
> CIK, DateFiled, SECWebAddress FROM SEC_Index_01" +
> "";
> this.sqlSelectCommand1.Connection = this.sqlConnection1;
> //
> // sqlInsertCommand1
> //
> this.sqlInsertCommand1.CommandText = "INSERT INTO
> SEC_Index_01(CompanyName, FormType, CIK, DateFiled, SECWebAddress) VA" +
> "LUES (@.CompanyName, @.FormType, @.CIK, @.DateFiled, @.SECWebAddress);
> SELECT ID, Com" +
> "panyName, FormType, CIK, DateFiled, SECWebAddress FROM SEC_Index_01
> WHERE (ID = " +
> "@.@.IDENTITY)";
> this.sqlInsertCommand1.Connection = this.sqlConnection1;
> this.sqlInsertCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.CompanyName",
> System.Data.SqlDbType.VarChar, 8000, "CompanyName"));
> this.sqlInsertCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.FormType",
> System.Data.SqlDbType.VarChar, 8000, "FormType"));
> this.sqlInsertCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.CIK", System.Data.SqlDbType.VarChar,
> 8000, "CIK"));
> this.sqlInsertCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.DateFiled",
> System.Data.SqlDbType.VarChar, 8000, "DateFiled"));
> this.sqlInsertCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.SECWebAddress",
> System.Data.SqlDbType.VarChar, 8000, "SECWebAddress"));
> //
> // sqlUpdateCommand1
> //
> this.sqlUpdateCommand1.CommandText = @."UPDATE SEC_Index_01 SET
> CompanyName = @.CompanyName, FormType = @.FormType, CIK = @.CIK, DateFiled =
> @.DateFiled, SECWebAddress = @.SECWebAddress WHERE (ID = @.Original_ID) AND
> (CIK
> = @.Original_CIK OR @.Original_CIK IS NULL AND CIK IS NULL) AND (CompanyName
> =
> @.Original_CompanyName OR @.Original_CompanyName IS NULL AND CompanyName IS
> NULL) AND (DateFiled = @.Original_DateFiled OR @.Original_DateFiled IS NULL
> AND
> DateFiled IS NULL) AND (FormType = @.Original_FormType OR
> @.Original_FormType
> IS NULL AND FormType IS NULL) AND (SECWebAddress = @.Original_SECWebAddress
> OR
> @.Original_SECWebAddress IS NULL AND SECWebAddress IS NULL); SELECT ID,
> CompanyName, FormType, CIK, DateFiled, SECWebAddress FROM SEC_Index_01
> WHERE
> (ID = @.ID)";
> this.sqlUpdateCommand1.Connection = this.sqlConnection1;
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.CompanyName",
> System.Data.SqlDbType.VarChar, 8000, "CompanyName"));
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.FormType",
> System.Data.SqlDbType.VarChar, 8000, "FormType"));
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.CIK", System.Data.SqlDbType.VarChar,
> 8000, "CIK"));
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.DateFiled",
> System.Data.SqlDbType.VarChar, 8000, "DateFiled"));
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.SECWebAddress",
> System.Data.SqlDbType.VarChar, 8000, "SECWebAddress"));
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_ID",
> System.Data.SqlDbType.Int,
> 4, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)),
> ((System.Byte)(0)), "ID", System.Data.DataRowVersion.Original, null));
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_CIK",
> System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
> false, ((System.Byte)(0)), ((System.Byte)(0)), "CIK",
> System.Data.DataRowVersion.Original, null));
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_CompanyName",
> System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
> false, ((System.Byte)(0)), ((System.Byte)(0)), "CompanyName",
> System.Data.DataRowVersion.Original, null));
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_DateFiled",
> System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
> false, ((System.Byte)(0)), ((System.Byte)(0)), "DateFiled",
> System.Data.DataRowVersion.Original, null));
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_FormType",
> System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
> false, ((System.Byte)(0)), ((System.Byte)(0)), "FormType",
> System.Data.DataRowVersion.Original, null));
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_SECWebAddress",
> System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
> false, ((System.Byte)(0)), ((System.Byte)(0)), "SECWebAddress",
> System.Data.DataRowVersion.Original, null));
> this.sqlUpdateCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.ID", System.Data.SqlDbType.Int, 4,
> "ID"));
> //
> // sqlDeleteCommand1
> //
> this.sqlDeleteCommand1.CommandText = @."DELETE FROM SEC_Index_01 WHERE (ID
> = @.Original_ID) AND (CIK = @.Original_CIK OR @.Original_CIK IS NULL AND CIK
> IS
> NULL) AND (CompanyName = @.Original_CompanyName OR @.Original_CompanyName IS
> NULL AND CompanyName IS NULL) AND (DateFiled = @.Original_DateFiled OR
> @.Original_DateFiled IS NULL AND DateFiled IS NULL) AND (FormType =
> @.Original_FormType OR @.Original_FormType IS NULL AND FormType IS NULL) AND
> (SECWebAddress = @.Original_SECWebAddress OR @.Original_SECWebAddress IS
> NULL
> AND SECWebAddress IS NULL)";
> this.sqlDeleteCommand1.Connection = this.sqlConnection1;
> this.sqlDeleteCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_ID",
> System.Data.SqlDbType.Int,
> 4, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)),
> ((System.Byte)(0)), "ID", System.Data.DataRowVersion.Original, null));
> this.sqlDeleteCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_CIK",
> System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
> false, ((System.Byte)(0)), ((System.Byte)(0)), "CIK",
> System.Data.DataRowVersion.Original, null));
> this.sqlDeleteCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_CompanyName",
> System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
> false, ((System.Byte)(0)), ((System.Byte)(0)), "CompanyName",
> System.Data.DataRowVersion.Original, null));
> this.sqlDeleteCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_DateFiled",
> System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
> false, ((System.Byte)(0)), ((System.Byte)(0)), "DateFiled",
> System.Data.DataRowVersion.Original, null));
> this.sqlDeleteCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_FormType",
> System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
> false, ((System.Byte)(0)), ((System.Byte)(0)), "FormType",
> System.Data.DataRowVersion.Original, null));
> this.sqlDeleteCommand1.Parameters.Add(new
> System.Data.SqlClient.SqlParameter("@.Original_SECWebAddress",
> System.Data.SqlDbType.VarChar, 8000, System.Data.ParameterDirection.Input,
> false, ((System.Byte)(0)), ((System.Byte)(0)), "SECWebAddress",
> System.Data.DataRowVersion.Original, null));
> //
> // sqlConnection1
> //
> this.sqlConnection1.ConnectionString = "workstation id=AMD;packet
> size=4096;integrated security=SSPI;data source=AMD;pers" +
> "ist security info=False;initial catalog=SEC_XBRL_10";
> //
> // dataSet11
> //
> this.dataSet11.DataSetName = "DataSet1";
> this.dataSet11.Locale = new System.Globalization.CultureInfo("en-US");
> //
> // Form1
> //
> this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
> this.ClientSize = new System.Drawing.Size(292, 273);
> this.Controls.Add(this.dataGrid1);
> this.Controls.Add(this.button1);
> this.Name = "Form1";
> this.Text = "Form1";
> ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
> ((System.ComponentModel.ISupportInitialize)(this.dataSet11)).EndInit();
> this.ResumeLayout(false);
> }
> #endregion
> /// <summary>
> /// The main entry point for the application.
> /// </summary>
> [STAThread]
> static void Main()
> {
> Application.Run(new Form1());
> }
> private void button1_Click(object sender, System.EventArgs e)
> {
> dataGrid1.DataSource=null; //Clear the
> datagrid
> sqlDataAdapter1.Fill(dataSet11,"SEC_Index_01"); //Fill result dataset
> with SEC_Index_01 table data via the sqlDataAdapter1
> //WebRequest req =
> WebRequest.Create("http://www.sec.gov/Archives/edgar/daily-index/" +
> "company." + "20041222" + ".idx"); // Create the Request object
> //WebResponse response = req.GetResponse(); //Create the
> Response object
> //Stream stream = response.GetResponseStream(); //Create a
> Stream
> //StreamReader sr = new StreamReader(stream); //Open the file
> in a stream reader
> StreamReader sr = new StreamReader("C:\\test.txt"); //Read From
> A File instead of a webrequest
> dataSet11.Tables.Add("MyNewTable"); //Add DataTable to
> hold the DataSet
> dataSet11.Tables["MyNewTable"].Columns.Add("CompanyName"); //Add a
> single column to the DataTable
> dataSet11.Tables["MyNewTable"].Columns.Add("FormType"); //Add a
> single column
> dataSet11.Tables["MyNewTable"].Columns.Add("CIK"); //Add a
> single column
> dataSet11.Tables["MyNewTable"].Columns.Add("DateFiled"); //Add a
> single column
> dataSet11.Tables["MyNewTable"].Columns.Add("SECWebAddress"); //Add a
> single column
> string AllData1 = sr.ReadToEnd(); //Read the rest
> of the data in the file.
> string[] rows = AllData1.Split("\n".ToCharArray()); //Split off
> each row at the Line Feed
> foreach(string r in rows) //Now add each
> row to the DataSet
> {
> string delimStr1 = "\t";
> string[] items = r.Split(delimStr1.ToCharArray()); //Split the row
> at the delimiter
> dataSet11.Tables["MyNewTable"].Rows.Add(items); //Add the item
> }
> for (int i = 1; i <= 11; i++) //Remove first 11
> rows from the DataTable/DataSet
> {
> dataSet11.Tables["MyNewTable"].Rows.RemoveAt(0);
> }
> sqlDataAdapter1.InsertCommand = sqlInsertCommand1; //Insert the new
> rows from the "result" dataset
> //sqlDataAdapter1.Update(dataSet11,"SEC_Index_01"); //Perform the
> update
> dataGrid1.SetDataBinding(dataSet11, "MyNewTable"); //Binds DataGrid to
> DataSet,displaying datatable.
> MessageBox.Show("Data has been added to the SQL Table SEC_XBRL_Index");
> }
> }
> }|||oj:
Thank You...your answer solved my problem. I'd buy you a drink if I could.
I suppose in retrospect that the answer is somewhat obvious, but not being
all that familiar with what code "I" needed to add to make the data adapters
work, it wasn't obvious to me at all.
Thanks,
Paul
========================================
=======
"oj" wrote:

> Here's the reply to your earlier post...
> A quick browse through your code, you have this line:
> sqlDataAdapter1.Update(dataSet11,"SEC_Index_01"); //Perform the
> update
> which sends the updates (i.e. insert, update, delete operation) to sqlserv
er
> for SEC_Index_01 table.
> You have to addrow to dataSet11.Tables["SEC_Index_01"] if you want the
> inserts!
> The gist of it is you would want to add this to your code before calling
> da.update.
> e.g.
> foreach(DataRow dr in dataSet11.Tables["MyNewTable"].Rows)
> {
> DataRow r = dataSet11.Tables["SEC_Index_01"].NewRow();
> r["CompanyName"] = dr["CompanyName"];
> // ... do the same for the rest of your columns
> dataSet11.Tables["SEC_Index_01"].Rows.Add(r);
> }
> --
> -oj|||You're welcome.
A virtual drink is welcome also. ;-)
-oj
"a" <a@.discussions.microsoft.com> wrote in message
news:82ACC91A-6558-4FBC-A06A-486477197C42@.microsoft.com...
> oj:
> Thank You...your answer solved my problem. I'd buy you a drink if I could.
> I suppose in retrospect that the answer is somewhat obvious, but not being
> all that familiar with what code "I" needed to add to make the data
> adapters
> work, it wasn't obvious to me at all.
> Thanks,
> Paul
> ========================================
=======
> "oj" wrote:
>
>

Inserting a checkbox value into bit field sql server 2000

Edited by SomeNewKid. Please post code between<code> and</code> tags.



This is probaly the easiest question you've ever read but here goes.

I have a simple checkbox value that i want to insert into the database but whatever i do it does not seem to let me.

Here is my code:

Sub AddSection_Click(Sender As Object, e As EventArgs)
Dim myCommand As SqlCommand
Dim insertCmd As String
' Build a SQL INSERT statement string for all the input-form
' field values.
insertCmd = "insert into Customers values (@.SectionName, @.SectionLink, @.Title, @.NewWindow, @.LatestNews, @.Partners, @.Support);"
' Initialize the SqlCommand with the new SQL string.
myCommand = New SqlCommand(insertCmd, myConnection)
' Create new parameters for the SqlCommand object and
' initialize them to the input-form field values.
myCommand.Parameters.Add(New SqlParameter("@.SectionName", SqlDbType.nVarChar, 50))
myCommand.Parameters("@.SectionName").Value = Section_name.Value

myCommand.Parameters.Add(New SqlParameter("@.SectionLink", SqlDbType.nVarChar, 80))
myCommand.Parameters("@.SectionLink").Value = Section_link.Value

myCommand.Parameters.Add(New SqlParameter("@.Title", SqlDbType.nVarChar, 50))
myCommand.Parameters("@.Title").Value = Section_title.Value

If New_window.Checked = false Then
myCommand.Parameters.Add(New SqlParameter("@.NewWindow", SqlDbType.bit, 1))
myCommand.Parameters("@.NewWindow").Value = 0
else
myCommand.Parameters.Add(New SqlParameter("@.NewWindow", SqlDbType.bit, 1))
myCommand.Parameters("@.NewWindow").Value = 1
End If

If Latest_news.Checked = false Then
myCommand.Parameters.Add(New SqlParameter("@.LatestNews", SqlDbType.bit, 1))
myCommand.Parameters("@.LatestNews").Value = 0
else
myCommand.Parameters.Add(New SqlParameter("@.LatestNews", SqlDbType.bit, 1))
myCommand.Parameters("@.LatestNews").Value = 1
End If

If Partners.Checked = false Then
myCommand.Parameters.Add(New SqlParameter("@.Partners", SqlDbType.bit, 1))
myCommand.Parameters("@.Partners").Value = 0
else
myCommand.Parameters.Add(New SqlParameter("@.Partners", SqlDbType.bit, 1))
myCommand.Parameters("@.Partners").Value = 1
End If

If Support.Checked = false Then
myCommand.Parameters.Add(New SqlParameter("@.Support", SqlDbType.bit, 1))
myCommand.Parameters("@.Support").Value = 0
else
myCommand.Parameters.Add(New SqlParameter("@.Support", SqlDbType.bit, 1))
myCommand.Parameters("@.Support").Value = 1
End If

myCommand.Connection.Open()
' Test whether the new row can be added and display the
' appropriate message box to the user.
Try
myCommand.ExecuteNonQuery()
Message.InnerHtml = "Record Added<br>" & insertCmd
Catch ex As SqlException
If ex.Number = 2627 Then
Message.InnerHtml = "ERROR: A record already exists with " _
& "the same primary key"
Else
Message.InnerHtml = "ERROR: Could not add record, please " _
& "ensure the fields are correctly filled out"
Message.Style("color") = "red"
End If
End Try

myCommand.Connection.Close()
BindGrid()
End Sub

Any response would be appreciatedYou're right; it's easier than you think. Try this:

myCommand.Parameters.Add(New SqlParameter("@.Partners", SqlDbType.bit, 1))
myCommand.Parameters("@.Partners").Value = Partners.Checked

|||thanks a lot and sorry for the late reply that worked

Inserting 1 row and getting a message that two rows were inserted.

Why does this code tell me that I inserted 2 rows when I really only inserted one? I am using SQL server 2005 Express. I can open up the table and there is only one record in it.

Dim InsertSQL As String = "INSERT INTO dbCG_Disposition ( BouleID, UserName, CG_PFLocation ) VALUES ( @.BouleID, @.UserName, @.CG_PFLocation )"
Dim StatusAs Label = lblStatusDim ConnectionStringAs String = WebConfigurationManager.ConnectionStrings("HTALNBulk").ConnectionStringDim conAs New SqlConnection(ConnectionString)Dim cmdAs New SqlCommand(InsertSQL, con) cmd.Parameters.AddWithValue("BouleID", BouleID) cmd.Parameters.AddWithValue("UserName", UserID) cmd.Parameters.AddWithValue("CG_PFLocation", CG_PFLocation)Dim addedAs Integer = 0Try con.Open() added = cmd.ExecuteNonQuery() Status.Text &= added.ToString() &" records inserted into CG Process Flow Inventory, Located in Boule_Storage."Catch exAs Exception Status.Text &="Error adding to inventory. " Status.Text &= ex.Message.ToString()Finally con.Close()End Try

Anyone have any ideas? Thanks

Change

Status.Text &=

To

Status.Text =

When you put &=, every time when you fire event, the text will be appended

(After I posted it, I realized probably it was able to solve your issue. Sorry for that).

|||

Yeah, somehow, added is getting set to 2 at the

added = cmd.ExecuteNonQuery()
step. I have a trigger set on this table to increase other rows with the same BouleID by one but that shouldn't
affect the ADO object should it?
 
There is this in the MSDN:

Although theExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data.

ForUPDATE, INSERT, and DELETE statements, the return value is the numberof rows affected by the command. When a trigger exists on a table beinginserted or updated, the return value includes the number of rowsaffected by both the insert or update operation and the number of rowsaffected by the trigger or triggers. For all other types of statements,the return value is -1. If a rollback occurs, the return value is also-1.

The problem is that these are new inserts into the table so the trigger is not affecting any other rows because they don't exist yet.
|||

Quite possibly. Do you have a SET NOCOUNT ON in your triggers?

|||

No, I dont'. I only have

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

set.

|||

In your trigger, right after the "AS", add "SET NOCOUNT ON". Then any queries the trigger does won't be seen. For example:

CREATE TRIGGER ...

AS

SET NOCOUNT ON

...

Monday, March 26, 2012

Insert with Parameters (SQL Server)

Hello, this is my code:

SqlCommand cmd =new SqlCommand("INSERT INTO Users (Username,Password) " +"VALUES ('@.username','@.password' ",new SqlConnection(my_ConnectionString)); cmd.Parameters.Add("@.username", SqlDbType.NVarChar, 50).Value = txtUsername.Text;cmd.Parameters.Add("@.password", SqlDbType.NVarChar, 50).Value = txtPassword.Text cmd.Connection.Open();cmd.ExecuteNonQuery();cmd.Connection.Close();

But in the database, the row inserted is exactly this:

"@.username" "@.password"

I mean, the parameters are not inserted :S

Please, tell me the error in the code...
Thank you so much,

Carlos.Placing single quotes around the parameters makes them be treated as literal strings. Remove the single quotes and you should have better luck.|||Thank you, now it works ;)

Carlos.

Insert Values Error

Hey Guys:

I am trying to create a form, and then insert the values entered by a user into a sql database, I have enclosed the page code below. Everything works except the data is not being inserted into the database, and i keep getting the default message in my error message section. I took this right from the quick start tutorial and started working with it, and keep getting an error.

I believe the error is located in the INSERT statement


<%@. Page Language="vb" %>
<%@. Import Namespace="System.Data" %>
<%@. Import Namespace="System.Data.SqlClient" %
<html
<script language="VB" runat="server"
Dim MyConnection As SqlConnection

Sub Page_Load(Sender As Object, E As EventArgs)

MyConnection = New SqlConnection("server=localhost;database=planetauction;uid=planetauction;pwd=bean13")

If Not (IsPostBack)
BindGrid()
Page.DataBind()
End If
End Sub

Sub AddAuthor_Click(Sender As Object, E As EventArgs)
Page.Validate()
If Not Page.IsValid
Return
End If

Dim DS As DataSet
Dim MyCommand As SqlCommand

If txtLastName.Value = ""
Message.InnerHtml = "ERROR: Null values not allowed for Author ID, " & _
"Name or Phone"
Message.Style("color") = "red"
BindGrid()
Return
End If

Dim InsertCmd As String = "insert into users (txtLastName) values (@.lastname)"

MyCommand = New SqlCommand(InsertCmd, MyConnection)

MyCommand.Parameters.Add(New SqlParameter("@.lastname", SqlDbType.NVarChar, 50))
MyCommand.Parameters("@.lastname").Value = txtLastName.Value

MyCommand.Connection.Open()

Try
MyCommand.ExecuteNonQuery()
Message.InnerHtml = "Record Added<br>" & InsertCmd.ToString()

Catch Exp As SQLException
If Exp.Number = 2627
Message.InnerHtml = "ERROR: A record already exists with the " & _
"same primary key"
Else
Message.InnerHtml = "ERROR: Could not add record, please ensure " & _
"the fields are correctly filled out"
End If
Message.Style("color") = "red"

End Try

MyCommand.Connection.Close()

BindGrid()
End Sub

Sub BindGrid()

Dim MyCommand As SqlDataAdapter = new SqlDataAdapter( _
"select * from users", MyConnection)

Dim DS As DataSet = new DataSet()
MyCommand.Fill(DS, "Users")

MyDataGrid.DataSource=DS.Tables("Users").DefaultView
MyDataGrid.DataBind()
End Sub

</script
<body style="font: 10pt verdana"
<form runat="server" ID="Form1"
<h3><font face="Verdana">Inserting a Row of Data</font></h3
<table width="95%">
<tr>
<td valign="top"
<ASP:DataGrid id="MyDataGrid" runat="server"
Width="700"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
EnableViewState="false"
/
</td>
<td valign="top"
<table style="font: 8pt verdana">
<tr>
<td colspan="2" bgcolor="#aaaadd" style="font:10pt verdana">Add a New Author:</td>
</tr>
<tr>
<td nowrap>Last Name: </td>
<td>
<input type="text" id="txtLastName" runat="server" NAME="txtLastName"><br
</td>
</tr>
<tr>
<td></td>
<td style="padding-top:15">
<input type="submit" OnServerClick="AddAuthor_Click" value="Add Author" runat="server" ID="Submit1" NAME="Submit1">
</td>
</tr>
<tr>
<td colspan="2" style="padding-top:15" align="center">
<span id="Message" EnableViewState="false" style="font: arial 11pt;" runat="server"/>
</td>
</tr>
</table
</td>
</tr>
</table
</form
</body>
</html>

Put a more specific error message in while debugging:

Try
MyCommand.ExecuteNonQuery()
Message.InnerHtml = "Record Added<br>" & InsertCmd.ToString()
Catch Exp As SQLException
If Exp.Number = 2627
Message.InnerHtml = "ERROR: A record already exists with the " & _
"same primary key"
Else
Message.InnerHtml = "ERROR: Could not add record, please ensure " & _
"the fields are correctly filled out. Exception: " & Exp.ToString()
End If

Message.Style("color") = "red"

End Try

|||Mr. Reily:

Thanks for your advice. I added the detailed error message and here is what I got:

ERROR: Could not add record, please ensure the fields are correctly filled out. Exception: System.Data.SqlClient.SqlException: Invalid column name 'txtLastName'. at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at ASP.reference3_aspx.AddAuthor_Click(Object Sender, EventArgs E) in http://localhost/planetauction/reference3.aspx:line 47

I really think the error is in the insert statement. I need to put either double or single quotes around something in the insert statement, right now the database believes the value is referring to a column name, rather than inserting that data into the column specified.

Let me know what u think.

Thanks|||Thanks guys, got it all figured out.

It was the insert statment that was screwed up. For anyone else with the same problem, I simply mixed up the values, and the column names in the sql insert statements.

For Reference:

Dim InsertCmd As String = "insert into users (COLUMNNAME1, COLUMNNAME2) values (@.FIRST SQL PARAMETER LISTED BELOW, SECOND SQL PARAMETER LISTED BELOW, etc)"

MyCommand = New SqlCommand(InsertCmd, MyConnection)

MyCommand.Parameters.Add(New SqlParameter("@.lastname", SqlDbType.NVarChar, 50))
MyCommand.Parameters("@.lastname").Value = txtLastName.Value

MyCommand.Connection.Open()

Friday, March 23, 2012

Insert Trigger with If Statement

I want to check if a field has a 0 in it, if it does it should run some
code, if not do nothing
If field1 = 0 then
some code
end if
Please advise of the syntax for this
TIA PaulTry something on these lines:
If Exists (Select 1 from <Table> where field = 0)
Begin
-- the activity you wanted to do
End
--
HTH,
Vinod Kumar
MCSE, DBA, MCAD, MCSD
http://www.extremeexperts.com
http://groups.msn.com/SQLBang
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinfo/productdoc/2000/books.asp
"Paul Goldney" <paulg@.wizardit.co.uk> wrote in message
news:ca97dk$pm3$1$8302bc10@.news.demon.co.uk...
> I want to check if a field has a 0 in it, if it does it should run some
> code, if not do nothing
> If field1 = 0 then
> some code
> end if
> Please advise of the syntax for this
> TIA Paul
>|||Remember that more than one row may be inserted at once. Maybe one row = 0
and another row is <> 0. Probably you just need a WHERE clause on whatever
statement(s) are in "some code" instead of an IF statement:
?
...
FROM Inserted WHERE col = 0
You can test for col = 0 in an IF statement using EXISTS but crucially this
tests for the presence of *any* row where col = 0, which may or may not be
what you want in your trigger.
IF EXISTS
(SELECT *
FROM Inserted
WHERE col = 0)
--
David Portas
SQL Server MVP
--sql

Monday, March 12, 2012

Insert statement for a datetime field from vb.net code

Hi All,
I have a datetime column in a table on the SQL database. I need to insert
values into the datetime column from vb.net code. Here is my code:
dim nameval, str, qry as string
nameval = "abc"
str = "2005/03/16 14:20"
qry = "insert into tab1(name,dateval) values(" & "'" & nameval & "'," & "'"
str & "')"
...
...
ocmd.ExecuteNonQuery()
...
...
The error message that I get is as follows:
"The conversion of a char data type to a datetime data type resulted in an
out-of-range datetime value. The statement has been terminated. .Net
SqlClient Data Provider"
The problem I think is due to passing a string for a datetime field. My
question is, if I convert the string to datetype using CDate(str), then I
would have to again convert the date to string in order to form the insert
statement. So, the ultimate result will be again passing a string for the
datetime field!
I know that this is a simple syntax problem, which I don't seem to get right!
Would anybody be able to give me insert statement for the above?
Thanks.
kd
Hi
"2005/03/16 14:20" is not a valid date time value. Either use "2005-03-16
14:20:00" or "20050316 14:20:00"
Regards
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"kd" <kd@.discussions.microsoft.com> wrote in message
news:1FF9F499-8589-4964-9F11-731F22E3D673@.microsoft.com...
> Hi All,
> I have a datetime column in a table on the SQL database. I need to insert
> values into the datetime column from vb.net code. Here is my code:
> dim nameval, str, qry as string
> nameval = "abc"
> str = "2005/03/16 14:20"
> qry = "insert into tab1(name,dateval) values(" & "'" & nameval & "'," &
"'"
> str & "')"
> ...
> ..
> ocmd.ExecuteNonQuery()
> ...
> ...
> The error message that I get is as follows:
> "The conversion of a char data type to a datetime data type resulted in an
> out-of-range datetime value. The statement has been terminated. .Net
> SqlClient Data Provider"
> The problem I think is due to passing a string for a datetime field. My
> question is, if I convert the string to datetype using CDate(str), then I
> would have to again convert the date to string in order to form the insert
> statement. So, the ultimate result will be again passing a string for the
> datetime field!
> I know that this is a simple syntax problem, which I don't seem to get
right!
> Would anybody be able to give me insert statement for the above?
> Thanks.
> kd
>

INSERT statement conflicted with COLUMN CHECK constraint.

Hi,
I'm attempting to insert a new row into an SQL table using ADO written
with c# and stored procedures.
The ADO code is running OK, and i know it should work as i have used
equivilent code succeffully for other tables. However i am getting the
following error:
{"INSERT statement conflicted with COLUMN CHECK constraint 'CK
tblPatient pntStage'. The conflict occurred in database 'YLCdbSQL',
table 'tblPatient', column 'pntStage'.\r\nThe statement has been
terminated." }
pntStage has data type NVarChar, and maximum length 8. The values i am
attempting to input do not violate these criteria. I have deleted the
complete row and added it again incase there was some hidden input
mask, this has not solved the problem.
Any ideas what the problem might be? Here's my stored procedure if
taht's any help.
CREATE PROCEDURE proc_InsertPatient
(@.patientNo int output,
@.pntUnitID nvarchar(15),
@.pntTitle nvarchar(4),
@.pntFName nvarchar(20),
@.pntLName nvarchar(30),
@.pntDOB nvarchar(8),
@.pntSex nvarchar(1),
@.pntAddress1 nvarchar(150),
@.pntAddress2 nvarchar(150),
@.pntAddress3 nvarchar(150),
@.pntCountryNo int output,
@.pntPostcode nvarchar (10),
@.pntHPhone nvarchar (14),
@.pntWPhone nvarchar (14),
@.pntMobPhone nvarchar (14),
@.pntEmail nvarchar (50),
@.pntStage nvarchar (8),
@.pntT tinyint,
@.pntN tinyint,
@.pntM tinyint,
@.pntPreviousTreatments char (1000),
@.pntFurtherNotes char (1000)
)
AS
INSERT INTO tblPatient (pntUnitID, pntTitle, pntFName, pntLName,
pntDOB, pntSex, pntAddress1,
pntAddress2, pntAddress3, pntCountryNo, pntPostcode, pntHPhone,
pntWPhone,
pntMobPhone, pntEmail, pntStage, pntT, pntN, pntM,
pntPreviousTreatments, pntFurtherNotes)
VALUES
(@.pntUnitID, @.pntTitle, @.pntFName, @.pntLName, @.pntDOB, @.pntSex,
@.pntAddress1,
@.pntAddress2, @.pntAddress3, @.pntCountryNo, @.pntPostcode, @.pntHPhone,
@.pntWPhone,
@.pntMobPhone, @.pntEmail, @.pntStage, @.pntT, @.pntN, @.pntM,
@.pntPreviousTreatments, @.pntFurtherNotes)
SELECT @.patientNo=@.@.IDENTITY
GO
Thanks.Hi
pntStage might have a check constraint that specifics that the values can
only be in a certain range or of a certain patters. Look at the Column's
check constrains though EM to see what has been setup.
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"Assimalyst" <c_oxtoby@.hotmail.com> wrote in message
news:1122817569.583719.19100@.g43g2000cwa.googlegroups.com...
> Hi,
> I'm attempting to insert a new row into an SQL table using ADO written
> with c# and stored procedures.
> The ADO code is running OK, and i know it should work as i have used
> equivilent code succeffully for other tables. However i am getting the
> following error:
> {"INSERT statement conflicted with COLUMN CHECK constraint 'CK
> tblPatient pntStage'. The conflict occurred in database 'YLCdbSQL',
> table 'tblPatient', column 'pntStage'.\r\nThe statement has been
> terminated." }
> pntStage has data type NVarChar, and maximum length 8. The values i am
> attempting to input do not violate these criteria. I have deleted the
> complete row and added it again incase there was some hidden input
> mask, this has not solved the problem.
> Any ideas what the problem might be? Here's my stored procedure if
> taht's any help.
> CREATE PROCEDURE proc_InsertPatient
> (@.patientNo int output,
> @.pntUnitID nvarchar(15),
> @.pntTitle nvarchar(4),
> @.pntFName nvarchar(20),
> @.pntLName nvarchar(30),
> @.pntDOB nvarchar(8),
> @.pntSex nvarchar(1),
> @.pntAddress1 nvarchar(150),
> @.pntAddress2 nvarchar(150),
> @.pntAddress3 nvarchar(150),
> @.pntCountryNo int output,
> @.pntPostcode nvarchar (10),
> @.pntHPhone nvarchar (14),
> @.pntWPhone nvarchar (14),
> @.pntMobPhone nvarchar (14),
> @.pntEmail nvarchar (50),
> @.pntStage nvarchar (8),
> @.pntT tinyint,
> @.pntN tinyint,
> @.pntM tinyint,
> @.pntPreviousTreatments char (1000),
> @.pntFurtherNotes char (1000)
> )
> AS
> INSERT INTO tblPatient (pntUnitID, pntTitle, pntFName, pntLName,
> pntDOB, pntSex, pntAddress1,
> pntAddress2, pntAddress3, pntCountryNo, pntPostcode, pntHPhone,
> pntWPhone,
> pntMobPhone, pntEmail, pntStage, pntT, pntN, pntM,
> pntPreviousTreatments, pntFurtherNotes)
> VALUES
> (@.pntUnitID, @.pntTitle, @.pntFName, @.pntLName, @.pntDOB, @.pntSex,
> @.pntAddress1,
> @.pntAddress2, @.pntAddress3, @.pntCountryNo, @.pntPostcode, @.pntHPhone,
> @.pntWPhone,
> @.pntMobPhone, @.pntEmail, @.pntStage, @.pntT, @.pntN, @.pntM,
> @.pntPreviousTreatments, @.pntFurtherNotes)
> SELECT @.patientNo=@.@.IDENTITY
> GO
>
> Thanks.
>|||Please post the table DDL (including the CHECK constraint) and the @.pntStage
value you are trying to insert. This will help us identify the cause of
your problem.

> I have deleted the
> complete row and added it again incase there was some hidden input
> mask, this has not solved the problem.
I'm not sure I understand what you mean by 'deleted the complete row'.
Since the insert failed, I wouldn't expect you would find the row in
tblPatient.
Hope this helps.
Dan Guzman
SQL Server MVP
"Assimalyst" <c_oxtoby@.hotmail.com> wrote in message
news:1122817569.583719.19100@.g43g2000cwa.googlegroups.com...
> Hi,
> I'm attempting to insert a new row into an SQL table using ADO written
> with c# and stored procedures.
> The ADO code is running OK, and i know it should work as i have used
> equivilent code succeffully for other tables. However i am getting the
> following error:
> {"INSERT statement conflicted with COLUMN CHECK constraint 'CK
> tblPatient pntStage'. The conflict occurred in database 'YLCdbSQL',
> table 'tblPatient', column 'pntStage'.\r\nThe statement has been
> terminated." }
> pntStage has data type NVarChar, and maximum length 8. The values i am
> attempting to input do not violate these criteria. I have deleted the
> complete row and added it again incase there was some hidden input
> mask, this has not solved the problem.
> Any ideas what the problem might be? Here's my stored procedure if
> taht's any help.
> CREATE PROCEDURE proc_InsertPatient
> (@.patientNo int output,
> @.pntUnitID nvarchar(15),
> @.pntTitle nvarchar(4),
> @.pntFName nvarchar(20),
> @.pntLName nvarchar(30),
> @.pntDOB nvarchar(8),
> @.pntSex nvarchar(1),
> @.pntAddress1 nvarchar(150),
> @.pntAddress2 nvarchar(150),
> @.pntAddress3 nvarchar(150),
> @.pntCountryNo int output,
> @.pntPostcode nvarchar (10),
> @.pntHPhone nvarchar (14),
> @.pntWPhone nvarchar (14),
> @.pntMobPhone nvarchar (14),
> @.pntEmail nvarchar (50),
> @.pntStage nvarchar (8),
> @.pntT tinyint,
> @.pntN tinyint,
> @.pntM tinyint,
> @.pntPreviousTreatments char (1000),
> @.pntFurtherNotes char (1000)
> )
> AS
> INSERT INTO tblPatient (pntUnitID, pntTitle, pntFName, pntLName,
> pntDOB, pntSex, pntAddress1,
> pntAddress2, pntAddress3, pntCountryNo, pntPostcode, pntHPhone,
> pntWPhone,
> pntMobPhone, pntEmail, pntStage, pntT, pntN, pntM,
> pntPreviousTreatments, pntFurtherNotes)
> VALUES
> (@.pntUnitID, @.pntTitle, @.pntFName, @.pntLName, @.pntDOB, @.pntSex,
> @.pntAddress1,
> @.pntAddress2, @.pntAddress3, @.pntCountryNo, @.pntPostcode, @.pntHPhone,
> @.pntWPhone,
> @.pntMobPhone, @.pntEmail, @.pntStage, @.pntT, @.pntN, @.pntM,
> @.pntPreviousTreatments, @.pntFurtherNotes)
> SELECT @.patientNo=@.@.IDENTITY
> GO
>
> Thanks.
>|||Mike,
Thanks for the quick reply.
I've looked in EM at the tblPatient table. Within it's properties i can
only see row Name (pntStage), Data Type (nvarchar), Size (8), Nulls
(not allowed), Default (blank).
Is this what you mean? Is there another way to check more detailed
constraints?
Thanks again.|||Hi
In EM, when you are in the Table Edit screen, top left next to the save
button is the Properties button. On the check constraints tab, you can see
what columns have constraints and what they are.
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"Assimalyst" <c_oxtoby@.hotmail.com> wrote in message
news:1122818859.232265.305760@.g14g2000cwa.googlegroups.com...
> Mike,
> Thanks for the quick reply.
> I've looked in EM at the tblPatient table. Within it's properties i can
> only see row Name (pntStage), Data Type (nvarchar), Size (8), Nulls
> (not allowed), Default (blank).
> Is this what you mean? Is there another way to check more detailed
> constraints?
> Thanks again.
>|||Dan,
Excuse my ignorance, but where do i find the table DDL?
As regards the input value, i have tried a few "Unknown", "I", "II",
"Ia", to name a few.
By the deleting row comment, i was just meaning that it didn't work, so
i completely removed that particular row from the table, then recreated
it. I thought perhaps i might have put some sort of input mask
constraint or something on it that i had forgotten about. By doing this
it would remove that possibility.
Thanks.|||Mike,
I've just done that, there were some constraints on it. not sure how
they got there, but i've altered them, problem solved! :)
Thank you very much!|||One method to generate the table DDL is to navigate to the table using the
Query Analyzer Object Browser and then right-click on the table and select
script to clipboard as create. You can then paste into your post.
Hope this helps.
Dan Guzman
SQL Server MVP
"Assimalyst" <c_oxtoby@.hotmail.com> wrote in message
news:1122819272.357946.52430@.f14g2000cwb.googlegroups.com...
> Dan,
> Excuse my ignorance, but where do i find the table DDL?
> As regards the input value, i have tried a few "Unknown", "I", "II",
> "Ia", to name a few.
> By the deleting row comment, i was just meaning that it didn't work, so
> i completely removed that particular row from the table, then recreated
> it. I thought perhaps i might have put some sort of input mask
> constraint or something on it that i had forgotten about. By doing this
> it would remove that possibility.
> Thanks.
>|||You might want to find out WHY someone put constraints on the data.
Having a default of a blank on what should be a code is a sign that
someone did not do much design work. Of course we know that when we
saw the "tbl;" and "pnt-" prefixes that violation basic rules for
naming data elements. The "tbl-" prefix is silly in a language with
one data structure; the "pnt-" tells us the location f one occurence of
a data element, not what it is. When you wrote "pntSex" did you mean
"sex_code", "sex_frequency", "sex_preference", "sex_total"? Again,
name it for what it is, never for where it is.
And the use of NVARCHAR(n) in codes is usually a sign the nobody
designed the encodings; we prefer CHAR(n) so can add constraints and do
validation. Do you really use a lot of Chinese characters? If you
allow it, it will come.

Friday, March 9, 2012

INSERT rows while SELECT returning large volumes of data against same table

I'm taking over some legacy coding and am checking to see if there may be a better approach to some sql code I've inherited.
Any input would be appreciated.

Here was the problem that the implemented code was to address:

Given a high volume (10 to 50 thousand inserts daily) transaction table, it was observed that when executing a stored procedure that executed a
SELECT against the table while inserts were being attempted, there was considerable delay before the inserts were committed. It turns out the SELECT query was taking 100% CPU. Because of the business needs of the environment, the inserts were required to be committed in a very timely fashion.

Present Solution:

The currently implemented workaround implements a cursor that after so may reads will execute
the WAITFOR command in order to yield the CPU. This is all done within a stored procedure where there are actually seven
sections that parse through data tables in order to populate the temp table.

The below is just a example of the currently implemented code that invokes the waitfor command.

DECLARE @.a1 [datetime]
DECLARE @.b1 [int]
DECLARE @.c1 [int]
DECLARE @.rowCount [int]
DECLARE @.sleepRowCount [int]
DECLARE @.waitForDelay varchar(20)
DECLARE @.parameterDate1 smalldatetime

DECLARE @.parameterDate2 smallDateTime

SET @.parameterDate1 = '1/1/2006'

SET @.parameterDate2 = '1/31/2006'


SET @.sleepRowCount = 10000
SET @.waitForDelay = '0:0:0.500'
CREATE TABLE [#tempTable] (
a smalldatetime,
b int,
c int
)
DECLARE tableCursor CURSOR FOR
SELECT my.somedate, my.someId, count(*)
FROM myTable my with (nolock, index=IX_somedate)
WHERE my.somedate BETWEEN @.parameterDate1 AND @.parameterDate2
GROUP BY my.somedate, my.someId
OPEN tableCursor
FETCH NEXT FROM tableCursor INTO @.a1, @.b1, @.c1
WHILE @.@.FETCH_STATUS = 0
BEGIN
SET @.rowCount = @.rowCount + 1
INSERT INTO #tempTable VALUES( @.a1, @.b1, @.c1 )
FETCH next FROM tableCursor INTO @.a1, @.b1, @.c1
-- Yield CPU
IF (@.rowCount > @.sleepRowCount)
BEGIN
WAITFOR delay @.waitForDelay
SET @.rowCount=0
END
END
CLOSE tableCursor
DEALLOCATE tableCursor

Zymore:

What is the composition of the "IX_somedate" index? Does this index contain both (1) someDate and (2) someId?

Dave

|||

If you are directly inserting into the table without any modifications to the values retrieved you could directly dump the data into the temp table.

INSERT INTO #temptable

SELECT my.somedate, my.someId, count(*)
FROM myTable my with (nolock, index=IX_somedate)
WHERE my.somedate BETWEEN @.parameterDate1 AND @.parameterDate2
GROUP BY my.somedate, my.someId

|||

Mugambo

The sql code listed is just a rough example to give the reader an idea of the methodology that has been implemented to overcome CPU hogging. In the actual code, the date and id would be columns in a composite index that also contains additional columns.

Could high CPU use point to inefficient index usage from a query?

|||

Zymore:

Really, I think I would also implement pretty much the way Dinakar has laid it out. What I was puzzling over was the index hint -- wandering why the code needed to resort to an index hint. If you have a cover index -- and from your response it seems that you do -- then the index hint should not be necessary. My worry when I saw your example was that you were going to get bombarded with hundreds of thousands of bookmark lookups; and these could grieve you.

However, if you are getting your data out of a cover index and are not incurring any bookmark lookups then your insert and select should be very efficient. It would be a good idea to get an execution plan of the query you outlined and present it. Also, try Dinakar's query and get an execution for that particular query. Getting such execution plans would greatly help discussion. I will also put together a mock-up so that we can try to compare notes.


Dave

|||

Zymore:

I mocked up your table with about 98K records ranging in date from 1/1/2006 - 1/3/2006 and sprayed these records over 32K unique "someID" keys. I then ran your query and also ran Dinakar's query. I used two different nonclustered indexes for testing purposes; one version had only the "someDate" field and the other had both the "someDate" and the "someId" field. I ran the mock-up on my 4-way SQL Server 2000 machine. The information that I recorded included:

The particular index arrangement used|||

Mugambo wrote:

I left out something: After running the mockup I feel that Dinakar's query held up well. I would try Dinakar's query WITHOUT the INDEX HINT. And please make sure you thank Dinakar for his help.

Well, Mugambo has done all the (dirty) work. So credit goes to Mugambo.

|||You can improve the performance further by using SELECT...INTO instead of creating the temporary table first and doing INSERT. SELECT...INTO is the fastest way to create and populate a table. It does minimal logging so it doesn't have the same overhead as fully logged insert statement.

Wednesday, March 7, 2012

INSERT Records in multiple tables

I need to update two tables. I have created a view and am using the code in the attached file to insert into the two tables.

The page loads without errors, but I get this message that the view is not updatable because the modification affects multiple base tables.

I thought this was the purpose of views?

Does anyone have any suggestions? I am using Dreamweaver MX and SQL Server.

Thanks!
NNo, that is not the purpose of views. Views are frequently not updateable, and I don't think it is ever possible to update different columns from different tables in the same view. Even a direct SQL Update statement will only update one table at a time, so you will need to issues separate update statements or handle the problem through triggers or cascading updates.

Truth is, views don't serve much purpose any more.

Good database application design principles dictate making all your updates through stored procedures. Your application should rarely if ever have direct access to the database tables, even for retrieving data.|||No, you can update the columns of each of the base table independantly (one or more UPDATE statements per base table), but you can't update multiple base tables in a single pass.

Thinking outside of the SQL box, a table represents a relational algebra entity. An entity has no inherant order for either columns or rows, they behave something like a hash in that respect.

Views represent a relational algebra result. A result can have order, there can be a first, middle, and last for both rows and columns in a view.

-PatP|||Views (with multiple base tables) can be updated at one shot by using INSTEAD OF trigger

Here is some supporting article from MSDN

Cheers

Benny
-----------------------

Modifying Data Through a View
You can modify data through a view in these ways:

Use INSTEAD OF triggers with logic to support INSERT, UPDATE and DELETE statements.

Use updatable partitioned views that modify one or more member tables.
If a view does not use an INSTEAD OF trigger or is not an updatable partitioned view, it can still be updatable provided that:

The view contains at least one table in the FROM clause of the view definition; the view cannot be based solely on an expression.

No aggregate functions (AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR, VARP) or GROUP BY, UNION, DISTINCT, or TOP clauses are used in the select list. However, aggregate functions can be used within a subquery defined in the FROM clause provided that the derived values generated by the aggregate functions are not modified.

Note Partitioned views using the UNION ALL operator can be updatable.

No derived columns are used in the select list. Derived columns are result set columns formed by anything other than a simple column reference.
Guidelines for Modifying Data Through a View
Before you modify data through a view without using an INSTEAD OF trigger or an updatable partitioned view, consider these guidelines:

All data modification statements executed against the view must adhere to the criteria set within the SELECT statement defining the view if the WITH CHECK OPTION clause is used in the definition of the view. If the WITH CHECK OPTION clause is used, rows cannot be modified in a way that causes them to disappear from the view. Any modification that would cause this to happen is canceled and an error is displayed.

SQL Server must be able to resolve unambiguously the modification operation to specific rows in one of the base tables referenced by the view. You cannot use data modification statements on more than one underlying table in a single statement. Therefore, the columns listed in the UPDATE or INSERT statement must belong to a single base table within the view definition.

All the columns in the underlying table that are being updated and do not allow null values have values specified in either the INSERT statement or DEFAULT definitions. This ensures that all the columns in the underlying table that require values have them.

The data modified in the columns in the underlying table must adhere to the restrictions on those columns, such as nullability, constraints, DEFAULT definitions and so on. For example, if a row is deleted, all the underlying FOREIGN KEY constraints in related tables must still be satisfied for the delete to succeed.

A distributed partition view (remote view) cannot be updated using a keyset-driven cursor. This restriction can be resolved by declaring the cursor on the underlying tables and not on the view itself.
Additionally, to delete data in a view:

Only one table can be listed in the FROM clause of the view definition.|||Originally posted by blindman
Truth is, views don't serve much purpose any more.

what??!!

maybe not for use by the DBA, but for use by end users in a reporting environment, views are invaluable

"much purpose any more"?

what do you suppose the purpose of a view used to be then, before it got to where this purpose was diluted?

okay, here's an example

say a table is called Accounts and say it contains a column called LedgerCode and say the column values range from A to E, and now you have to change the table so that instead of values A to E, the LedgerCode becomes a numeric tinyint foreign key to a Ledger table with values A through Z

the mere fact that you can have a view with a join in it eliminates the need for the end user to figure out how to write a join

rename the table, change the table, declare a view called Accounts, build the join into the view, and voila, all existing code that used to select from the Accounts table still works

a long time ago i used to work in a shop where end users never got to use base tables, they were always given just views, and i can definitely see the logic behind that

it's called program-data independence|||Let me rephrase that...

Truth is, views don't serve much purpose any more, "IMHO".

I used to use views a lot too, specifically for program-data independence. Now, at least for application development, I always use Sprocs or UDFs.|||cool :cool:|||I believe you mean...

"Cool, IMHO." ;)|||indeed

burying application code inside sporcs and fuds is not cool to everybody, i admit -- especially those folks who would like to see a clear separation of application logic from proprietary database languages

usually i insist on declarative relational integrity but otherwise force application logic outside the database

you know, like so that your app is not dependent on any particular dbms

but sporcs and fuds are reasonably coolish, in my opinion, yeah|||Okey-dokey. I usually take the exact opposite approach, putting as much application logic into the RDBMS as possible, so that the application is not dependent on any particular interface. The reasoning is that these days people frequently want to access their data through different channels, such as a VB application, a Crystal Report, Access ADP project, Dot-Net, etc. By putting the application logic in the database you ensure consistent input and output and you avoid duplicating code. Let the the interface do what it does best: display the data and guide the user through it.

I guess the decision depends upon whether it is more likely that your application will need to be ported to a different RDBMS, or that users will come up with new requirements for accessing it. Perhaps I prefer the latter because the former results in boring "file cabinet" databases which frequently lack any sort of referential integrity. They just aren't as much fun or rewarding to work with as a database which is practically an application in itself.

INSERT query gets String data right truncation through ODBC but it works in SQL Server 7?

Hello Helpfull Helpers,
When I try to run an insert query from my Web site I get the following
error...
Error Diagnostic Information
ODBC Error Code = 22001 (String data right truncation)
[Microsoft][ODBC SQL Server Driver][SQL Server]String or binary data
would be truncated.
The error occurred while processing an element with a general
identifier of (CFQUERY), occupying document position (701:3) to
(701:73).
...but when I copy and paste the query into SQL Server Enterprise
Manager, the Insert succeeds.
Why does the query work in SQL Server Enterprise Manager but not from
my Web page? The Web page used to work fine.
My System Information:
======================
Windows 2000 Server (Operating System)
Cold Fusion 4.5 Server (Dynamic Web Server)
SQL Server 7.0 (Database Server)
The Query That Fails In The Web Page But Succeeds In Enterprise
Manager:
================================================== ======================
INSERT INTO dboJob(CUID, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12,
f13, f16, f17, f18, f19)
VALUES(
14036,
'09/17/2004 1:3:7 PM',
0,
'o',
'Testing new limit region functionality',
'Limit region should include cascading city, state or province,
country, and zip.',
'Fully functional.',
'',
'11',
'p',
'',
'',
'3',
'5',
0,
0 )
Table Information (field names have been changed to protect the
innocent):
================================================== ========================
CREATE TABLE [dbo].[dboJob] (
[JOID] [decimal](18, 0) IDENTITY (1, 1) NOT NULL ,
[CUID] [decimal](18, 0) NOT NULL ,
[f1] [varchar] (2) NOT NULL ,
[f2] [datetime] NOT NULL ,
[f3] [datetime] NOT NULL ,
[f4] [money] NOT NULL ,
[f5] [varchar] (1) NOT NULL ,
[f6] [varchar] (100) NULL ,
[f7] [varchar] (3000) NOT NULL ,
[f8] [varchar] (1500) NOT NULL ,
[f9] [varchar] (3000) NULL ,
[f10] [numeric](18, 0) NOT NULL ,
[f11] [char] (1) NOT NULL ,
[f12] [varchar] (200) NOT NULL ,
[f13] [varchar] (64) NULL ,
[f14] [varchar] (1) NOT NULL ,
[f15] [varchar] (1) NOT NULL ,
[f16] [varchar] (1) NOT NULL ,
[f17] [varchar] (1) NOT NULL ,
[f18] [money] NOT NULL ,
[f19] [money] NOT NULL ,
[f20] [datetime] NOT NULL
) ON [PRIMARY]
GO
Thanks,
Nate
I suggest you try the INSERT statement through QA. After the INSERT, check whether the data has been
truncated. Also, read about SET ANSI_WARNING.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"nate" <nathandeneau@.cox.net> wrote in message
news:4630acfb.0409141227.64eb7823@.posting.google.c om...
> Hello Helpfull Helpers,
> When I try to run an insert query from my Web site I get the following
> error...
> Error Diagnostic Information
> ODBC Error Code = 22001 (String data right truncation)
> [Microsoft][ODBC SQL Server Driver][SQL Server]String or binary data
> would be truncated.
> The error occurred while processing an element with a general
> identifier of (CFQUERY), occupying document position (701:3) to
> (701:73).
> ...but when I copy and paste the query into SQL Server Enterprise
> Manager, the Insert succeeds.
> Why does the query work in SQL Server Enterprise Manager but not from
> my Web page? The Web page used to work fine.
> My System Information:
> ======================
> Windows 2000 Server (Operating System)
> Cold Fusion 4.5 Server (Dynamic Web Server)
> SQL Server 7.0 (Database Server)
> The Query That Fails In The Web Page But Succeeds In Enterprise
> Manager:
> ================================================== ======================
> INSERT INTO dboJob(CUID, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12,
> f13, f16, f17, f18, f19)
> VALUES(
> 14036,
> '09/17/2004 1:3:7 PM',
> 0,
> 'o',
> 'Testing new limit region functionality',
> 'Limit region should include cascading city, state or province,
> country, and zip.',
> 'Fully functional.',
> '',
> '11',
> 'p',
> '',
> '',
> '3',
> '5',
> 0,
> 0 )
> Table Information (field names have been changed to protect the
> innocent):
> ================================================== ========================
> CREATE TABLE [dbo].[dboJob] (
> [JOID] [decimal](18, 0) IDENTITY (1, 1) NOT NULL ,
> [CUID] [decimal](18, 0) NOT NULL ,
> [f1] [varchar] (2) NOT NULL ,
> [f2] [datetime] NOT NULL ,
> [f3] [datetime] NOT NULL ,
> [f4] [money] NOT NULL ,
> [f5] [varchar] (1) NOT NULL ,
> [f6] [varchar] (100) NULL ,
> [f7] [varchar] (3000) NOT NULL ,
> [f8] [varchar] (1500) NOT NULL ,
> [f9] [varchar] (3000) NULL ,
> [f10] [numeric](18, 0) NOT NULL ,
> [f11] [char] (1) NOT NULL ,
> [f12] [varchar] (200) NOT NULL ,
> [f13] [varchar] (64) NULL ,
> [f14] [varchar] (1) NOT NULL ,
> [f15] [varchar] (1) NOT NULL ,
> [f16] [varchar] (1) NOT NULL ,
> [f17] [varchar] (1) NOT NULL ,
> [f18] [money] NOT NULL ,
> [f19] [money] NOT NULL ,
> [f20] [datetime] NOT NULL
> ) ON [PRIMARY]
> GO
> Thanks,
> Nate

INSERT query gets String data right truncation through ODBC but it works in SQL Server 7?

Hello Helpfull Helpers,
When I try to run an insert query from my Web site I get the following
error...
Error Diagnostic Information
ODBC Error Code = 22001 (String data right truncation)
[Microsoft][ODBC SQL Server Driver][SQL Server]String or binary data
would be truncated.
The error occurred while processing an element with a general
identifier of (CFQUERY), occupying document position (701:3) to
(701:73).
...but when I copy and paste the query into SQL Server Enterprise
Manager, the Insert succeeds.
Why does the query work in SQL Server Enterprise Manager but not from
my Web page? The Web page used to work fine.
My System Information:
====================== Windows 2000 Server (Operating System)
Cold Fusion 4.5 Server (Dynamic Web Server)
SQL Server 7.0 (Database Server)
The Query That Fails In The Web Page But Succeeds In Enterprise
Manager:
======================================================================== INSERT INTO dboJob(CUID, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12,
f13, f16, f17, f18, f19)
VALUES(
14036,
'09/17/2004 1:3:7 PM',
0,
'o',
'Testing new limit region functionality',
'Limit region should include cascading city, state or province,
country, and zip.',
'Fully functional.',
'',
'11',
'p',
'',
'',
'3',
'5',
0,
0 )
Table Information (field names have been changed to protect the
innocent):
========================================================================== CREATE TABLE [dbo].[dboJob] (
[JOID] [decimal](18, 0) IDENTITY (1, 1) NOT NULL ,
[CUID] [decimal](18, 0) NOT NULL ,
[f1] [varchar] (2) NOT NULL ,
[f2] [datetime] NOT NULL ,
[f3] [datetime] NOT NULL ,
[f4] [money] NOT NULL ,
[f5] [varchar] (1) NOT NULL ,
[f6] [varchar] (100) NULL ,
[f7] [varchar] (3000) NOT NULL ,
[f8] [varchar] (1500) NOT NULL ,
[f9] [varchar] (3000) NULL ,
[f10] [numeric](18, 0) NOT NULL ,
[f11] [char] (1) NOT NULL ,
[f12] [varchar] (200) NOT NULL ,
[f13] [varchar] (64) NULL ,
[f14] [varchar] (1) NOT NULL ,
[f15] [varchar] (1) NOT NULL ,
[f16] [varchar] (1) NOT NULL ,
[f17] [varchar] (1) NOT NULL ,
[f18] [money] NOT NULL ,
[f19] [money] NOT NULL ,
[f20] [datetime] NOT NULL
) ON [PRIMARY]
GO
Thanks,
NateI suggest you try the INSERT statement through QA. After the INSERT, check whether the data has been
truncated. Also, read about SET ANSI_WARNING.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"nate" <nathandeneau@.cox.net> wrote in message
news:4630acfb.0409141227.64eb7823@.posting.google.com...
> Hello Helpfull Helpers,
> When I try to run an insert query from my Web site I get the following
> error...
> Error Diagnostic Information
> ODBC Error Code = 22001 (String data right truncation)
> [Microsoft][ODBC SQL Server Driver][SQL Server]String or binary data
> would be truncated.
> The error occurred while processing an element with a general
> identifier of (CFQUERY), occupying document position (701:3) to
> (701:73).
> ...but when I copy and paste the query into SQL Server Enterprise
> Manager, the Insert succeeds.
> Why does the query work in SQL Server Enterprise Manager but not from
> my Web page? The Web page used to work fine.
> My System Information:
> ======================> Windows 2000 Server (Operating System)
> Cold Fusion 4.5 Server (Dynamic Web Server)
> SQL Server 7.0 (Database Server)
> The Query That Fails In The Web Page But Succeeds In Enterprise
> Manager:
> ========================================================================> INSERT INTO dboJob(CUID, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12,
> f13, f16, f17, f18, f19)
> VALUES(
> 14036,
> '09/17/2004 1:3:7 PM',
> 0,
> 'o',
> 'Testing new limit region functionality',
> 'Limit region should include cascading city, state or province,
> country, and zip.',
> 'Fully functional.',
> '',
> '11',
> 'p',
> '',
> '',
> '3',
> '5',
> 0,
> 0 )
> Table Information (field names have been changed to protect the
> innocent):
> ==========================================================================> CREATE TABLE [dbo].[dboJob] (
> [JOID] [decimal](18, 0) IDENTITY (1, 1) NOT NULL ,
> [CUID] [decimal](18, 0) NOT NULL ,
> [f1] [varchar] (2) NOT NULL ,
> [f2] [datetime] NOT NULL ,
> [f3] [datetime] NOT NULL ,
> [f4] [money] NOT NULL ,
> [f5] [varchar] (1) NOT NULL ,
> [f6] [varchar] (100) NULL ,
> [f7] [varchar] (3000) NOT NULL ,
> [f8] [varchar] (1500) NOT NULL ,
> [f9] [varchar] (3000) NULL ,
> [f10] [numeric](18, 0) NOT NULL ,
> [f11] [char] (1) NOT NULL ,
> [f12] [varchar] (200) NOT NULL ,
> [f13] [varchar] (64) NULL ,
> [f14] [varchar] (1) NOT NULL ,
> [f15] [varchar] (1) NOT NULL ,
> [f16] [varchar] (1) NOT NULL ,
> [f17] [varchar] (1) NOT NULL ,
> [f18] [money] NOT NULL ,
> [f19] [money] NOT NULL ,
> [f20] [datetime] NOT NULL
> ) ON [PRIMARY]
> GO
> Thanks,
> Nate

Friday, February 24, 2012

Insert querry

Hello

Can anyone give me the code to insert date from textbox to database(SQL Server 2000). The date fromat in SQL is dd-mm-yyyy.

Rathish

rathish,

here is some code if you wish to take the code behind approach.

string yourDate;yourDate = txtBox.Text;string insertStr ="insert into yourTable values ('" + yourDate +"')";SqlConnection conn =new SqlConnection(connectionStr);SqlCommand cmd =new SqlCommand(insertStr, conn);using(conn){using(cmd){ conn.Open(); cmd.ExecuteNonQuery(); }}you can try something like that. hope it helps! -- jp
|||

Hello

Its giving me the following error:

Syntax error convertig datetime from character string.

The datatype is datetime in the database.

Rathish

|||

Hi,

I would suggest you use parameters update database

string yourDate;
yourDate = txtBox.Text;
string insertStr = "insert into yourTable(datefield) values (@.datefield)";
SqlConnection conn = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(insertStr, conn);
cmd.Parameters.Add("@.datefield", SqlDbType.DateTime, 8)
cmd.Parameters["@.datefield"].Value = DateTime.Parse(yourDate)
using(conn){
using(cmd){
conn.Open();
cmd.ExecuteNonQuery();
}
}

HTH. If this does not answer your question, please feel free to mark the post as Not Answered and reply. Thank you!

Insert Problem.

I am using a DTS package to insert data into a SQL table. This has worked
correctly for the last 2 years. However when I run the code now I get a
Timeout error. I have rebooted the server with no success. If I try and run
the data into a temporary table it works fine.
Is the table corrupt ? If so how can I uncorrupt it ?
Si
Can you provide a little more information on where the table is stored, how
the dts package looks like?
What's the source? What's the destination?
Dandy Weyn
[MCSE-MCSA-MCDBA-MCDST-MCT]
http://www.dandyman.net
Check my SQL Server Resource Pages at http://www.dandyman.net/sql
"Simon" <Simon@.discussions.microsoft.com> wrote in message
news:CA096C29-74E5-48F2-923A-A00D2321BDF4@.microsoft.com...
>I am using a DTS package to insert data into a SQL table. This has worked
> correctly for the last 2 years. However when I run the code now I get a
> Timeout error. I have rebooted the server with no success. If I try and
> run
> the data into a temporary table it works fine.
> Is the table corrupt ? If so how can I uncorrupt it ?
> Si

Insert Problem.

I am using a DTS package to insert data into a SQL table. This has worked
correctly for the last 2 years. However when I run the code now I get a
Timeout error. I have rebooted the server with no success. If I try and run
the data into a temporary table it works fine.
Is the table corrupt ? If so how can I uncorrupt it ?
SiCan you provide a little more information on where the table is stored, how
the dts package looks like?
What's the source? What's the destination?
Dandy Weyn
[MCSE-MCSA-MCDBA-MCDST-MCT]
http://www.dandyman.net
Check my SQL Server Resource Pages at http://www.dandyman.net/sql
"Simon" <Simon@.discussions.microsoft.com> wrote in message
news:CA096C29-74E5-48F2-923A-A00D2321BDF4@.microsoft.com...
>I am using a DTS package to insert data into a SQL table. This has worked
> correctly for the last 2 years. However when I run the code now I get a
> Timeout error. I have rebooted the server with no success. If I try and
> run
> the data into a temporary table it works fine.
> Is the table corrupt ? If so how can I uncorrupt it ?
> Si

Sunday, February 19, 2012

INSERT or UPDATE syntax?

Oracle and a few other DB's contain a VERY nice "INSERT OR UPDATE" feature.
In my SQL Server code I have to have large IF blocks in order to replicate
this -- in a trigger or stored proc you don't know in advance which one
you're going to have to do.
Am I missing something here? Is there an easy way to replicate this feature
in SQL Server?
Maury
Nope, it's not there. Send a request for this feature to:
sqlwish@.microsoft.com
"Maury Markowitz" <MauryMarkowitz@.discussions.microsoft.com> wrote in
message news:DC54237D-E872-45A1-86F2-48F29665F9BD@.microsoft.com...
> Oracle and a few other DB's contain a VERY nice "INSERT OR UPDATE"
feature.
> In my SQL Server code I have to have large IF blocks in order to replicate
> this -- in a trigger or stored proc you don't know in advance which one
> you're going to have to do.
> Am I missing something here? Is there an easy way to replicate this
feature
> in SQL Server?
> Maury
|||There is no UPSERT or MERGE.
http://groups.google.com/groups?hl=e...phx.gbl#link1
http://groups.google.com/groups?hl=e...phx.gbl#link1
http://www.aspfaq.com/
(Reverse address to reply.)
"Maury Markowitz" <MauryMarkowitz@.discussions.microsoft.com> wrote in
message news:DC54237D-E872-45A1-86F2-48F29665F9BD@.microsoft.com...
> Oracle and a few other DB's contain a VERY nice "INSERT OR UPDATE"
feature.
> In my SQL Server code I have to have large IF blocks in order to replicate
> this -- in a trigger or stored proc you don't know in advance which one
> you're going to have to do.
> Am I missing something here? Is there an easy way to replicate this
feature
> in SQL Server?
> Maury

INSERT or UPDATE syntax?

Oracle and a few other DB's contain a VERY nice "INSERT OR UPDATE" feature.
In my SQL Server code I have to have large IF blocks in order to replicate
this -- in a trigger or stored proc you don't know in advance which one
you're going to have to do.
Am I missing something here? Is there an easy way to replicate this feature
in SQL Server?
MauryNope, it's not there. Send a request for this feature to:
sqlwish@.microsoft.com
"Maury Markowitz" <MauryMarkowitz@.discussions.microsoft.com> wrote in
message news:DC54237D-E872-45A1-86F2-48F29665F9BD@.microsoft.com...
> Oracle and a few other DB's contain a VERY nice "INSERT OR UPDATE"
feature.
> In my SQL Server code I have to have large IF blocks in order to replicate
> this -- in a trigger or stored proc you don't know in advance which one
> you're going to have to do.
> Am I missing something here? Is there an easy way to replicate this
feature
> in SQL Server?
> Maury|||There is no UPSERT or MERGE.
http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&frame=right&th=1bf4ff435f7820e3&seekm=uPfJ7%23jIEHA.2972%40TK2MSFTNGP12.phx.gbl#link1
http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&frame=right&th=cd0d91928e55b810&seekm=%23%241tZm0nEHA.3520%40TK2MSFTNGP11.phx.gbl#link1
--
http://www.aspfaq.com/
(Reverse address to reply.)
"Maury Markowitz" <MauryMarkowitz@.discussions.microsoft.com> wrote in
message news:DC54237D-E872-45A1-86F2-48F29665F9BD@.microsoft.com...
> Oracle and a few other DB's contain a VERY nice "INSERT OR UPDATE"
feature.
> In my SQL Server code I have to have large IF blocks in order to replicate
> this -- in a trigger or stored proc you don't know in advance which one
> you're going to have to do.
> Am I missing something here? Is there an easy way to replicate this
feature
> in SQL Server?
> Maury