OK i have my stored procedure all set up and working.. But when i try and add a second variable called @iuser and then after i execute the stored procedure, i get an error saying:-
ERROR
"Must declare scalar variable @iuser"
Here is the code i am using in my stored proc, also my stored proc worked fine before i used a second variable??!
//BEGIN
ALTER PROCEDURE [dbo].[putpending]
(@cuuser nvarchar(1000), @iuser nvarchar(1000))
And i know my VB.NET code is working but i will put it in anyway:-
//BEGIN
'variables
Dim user As String
user = Profile.UserName
Dim intenduser As String
intenduser = DetailsView1.Rows(0).Cells(1).Text.ToString()
'connection settings
Dim cs As String
cs = "Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|friends.mdf;Integrated Security=True;User Instance=True"
Dim scn As New SqlConnection(cs)
'parameters
Dim cmd As New SqlCommand("putpending", scn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@cuuser", SqlDbType.NVarChar, 1000)
cmd.Parameters("@cuuser").Value = user
cmd.Parameters.Add("@iuser", SqlDbType.NVarChar, 1000)
cmd.Parameters("@iuser").Value = intenduser
'execute
scn.Open()
Must declare the scalar variable "@Id_CostEmployee".
I'm tired of "googling" this error, and I've tried all the advices, nothing... I don't know what is happening here, I have 5 other forms, all simillar and they all work!
I'm making an ecommerce web app from following the Apress "Beginning ASP.Net 2 E-commerce with C#" book, and when I implement a stored procedure (I made a mdf DB in the app_Data folder), I get the following message: Must declare the scalar variable @CategoryIDThe code used to obtain this error is below: CREATE PROCEDURE DeleteCategory(@CategoryINT int)ASDELETE FROM CategoryWHERE CategoryID = @CategoryID I get this error with every Stored Procedure I try to implement. What should I do to fix this? In SQL Server 2k5 Management Studio, this problem does not present itself.
Hi with the code below I am getting the error Error inserting record. Must declare the scalar variable "@contractWHERE" I removed @contract and it then gave me the error Error inserting record. Must declare the scalar variable "@zipWHERE" I was wondering if some can point me in the right direction for fixxing this protected void cmdUpDate_Click(Object sender, EventArgs e) { //Define ADO.NET Objects. string updateSQL; updateSQL = "UPDATE Authors SET "; updateSQL += "au_id=@au_id, au_fname=@au_fname, au_lname=@au_lname, "; updateSQL += "phone=@phone, address=@address, city=@city,state=@state, "; updateSQL += "zip=@zip, contract=@contract"; updateSQL += "WHERE au_id@au_id_original"; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(updateSQL, con); //Add the parameters. cmd.Parameters.AddWithValue("@au_id", txtID.Text); cmd.Parameters.AddWithValue("@au_fname", txtFirstName.Text); cmd.Parameters.AddWithValue("@au_lname", txtLastName.Text); cmd.Parameters.AddWithValue("@phone", txtPhone.Text); cmd.Parameters.AddWithValue("@address", txtAddress.Text); cmd.Parameters.AddWithValue("@city", txtCity.Text); cmd.Parameters.AddWithValue("@state", txtState.Text); cmd.Parameters.AddWithValue("@zip", txtZip.Text); cmd.Parameters.AddWithValue("@contract", Convert.ToInt16(chkContract.Checked)); cmd.Parameters.AddWithValue("au_id_original", lstAuthor.SelectedItem.Value); //Try to open the database and execute the update try { con.Open(); int updated = cmd.ExecuteNonQuery(); lblStatus.Text = updated.ToString() + " records inserted."; } catch (Exception err) { lblStatus.Text = "Error inserting record. "; lblStatus.Text += err.Message; } finally { con.Close(); } } }
Following stored proc uses dynamic sql but it gives the error Msg 137, Level 15, State 2, Line 3 Must declare the scalar variable "@ProjectBenefitID". though its declared .please. tell the workaround
ALTER PROCEDURE [dbo].[spPMPT_GetBenefit]
@ProjectBenefitID INT,
@OrderBYVARCHAR(40), -- Parmeters for Paging [Start] @TotalPages INT OUT , @CurrentPageNumber INT OUT , @NumberOfRecordsINT = 5, /*PageSize*/ @CurrentPage INT = 0/*PageNumber*/
-- Parmeters for Paging [End]
AS
SET NOCOUNT ON
DECLARE @TMPFLOAT DECLARE @ErrorMsgID INT DECLARE@ErrorMsg VARCHAR(200)
----- Paging declarations start DECLARE @SQLFinal NVARCHAR(4000) DECLARE @Count INT DECLARE @SC VARCHAR(4000) ----- Paging declarations end
-- Initialize vars SET @SC= '' SET @From= '' SET @Where= '' SET @Select= '' SET @SQLFinal= '' SET @Count= 0
IF (@CurrentPage = 0 OR @CurrentPage IS NULL) BEGIN --Generate error message SELECT @ErrorMsg = 'Error occured in Stored Procedure ' + (SELECT name from sysobjects WHERE ID = @@PROCID) + '. The Page Number cannot be zero.' --Raise error to the user RAISERROR (@ErrorMsg,16/*severity*/,1/*state*/) --Return error indicator RETURN (-1) END IF (@NumberOfRecords = 0 OR @NumberOfRecords IS NULL ) BEGIN --Generate error message SELECT @ErrorMsg = 'Error occured in Stored Procedure ' + (SELECT name from sysobjects WHERE ID = @@PROCID) + '. Number of records per page cannot be zero.' --Raise error to the user RAISERROR (@ErrorMsg,16/*severity*/,1/*state*/) --Return error indicator RETURN (-1) END IF (@Orderby IS NULL OR @Orderby = '') BEGIN --Generate error message SELECT @ErrorMsg = 'Error occured in Stored Procedure ' + (SELECT name from sysobjects WHERE ID = @@PROCID) + '. The Order by cannot be null.' --Raise error to the user RAISERROR (@ErrorMsg,16/*severity*/,1/*state*/) --Return error indicator RETURN (-1) END
INSERT INTO #TEMP_BENEFIT1 SELECT AssessBenefitID,ProjectBenefitID, Quantity,Quality, Comments FROM PMPT_AssessBenefit WHERE ProjectBenefitID=@ProjectBenefitID AND AssessFlag='E' --and AssessBenefitID=@IterationID
INSERT INTO #TEMP_BENEFIT2 SELECT PAB.AssessBenefitID,PAB.ProjectBenefitID, PAB.Quantity,pab.qtyFileID, (SELECT FileName FROM PMPT_Files WHERE FileID = pab.qtyFileID) as QtyFileName, (SELECT UploadedFilePath FROM PMPT_Files WHERE FileID = pab.qtyFileID) as QtyFilepath, PAB.Quality,pab.quaFileID, (SELECT FileName FROM PMPT_Files WHERE FileID = pab.quaFileID) AS QualFileName, (SELECT UploadedFilePath FROM PMPT_Files WHERE FileID = pab.quaFileID) as QuaFilepath, PAB.Comments,PAB.refEXPAssessBenefitID,PAB.DateasON FROM PMPT_AssessBenefit PAB WHERE ProjectBenefitID=@ProjectBenefitID AND AssessFlag='A'
DECLARE @UNIT VARCHAR(100) SELECT @UNIT=NAME FROM PMPT_Picklists WHERE PicklistID = (SELECT unitID FROM PMPT_ProjectBenefits WHERE ProjectBenefitID=@ProjectBenefitID)
IF @UNIT IS NULL SET @UNIT = '' SET @Select=' DECLARE @UNIT VARCHAR(100) SELECT @UNIT=NAME FROM PMPT_Picklists WHERE PicklistID = (SELECT unitID FROM PMPT_ProjectBenefits WHERE ProjectBenefitID='+CONVERT(VARCHAR(10),@ProjectBenefitID))+' SELECTT1.AssessBenefitID, CAST(T1.ExpectedQuantity AS VARCHAR)+'' ''+ @UNIT as ExpectedQuantity, CAST( T2.ActualQuantity AS VARCHAR)+'' ''+ @UNIT as ActualQuantity, T2.QtyFileID, T2.QtyFileName AS QtyFileName ,T2.QtyFilepath, T1.ExpectedQuality AS ExpectedQuality , T2.ActualQuality AS ActualQuality , T2.QuaFileID,T2.QualFileName AS QualFileName ,T2.QualFilepath, T2.COMMENTS,CONVERT(VARCHAR(10),T2.DateasON,103) AS DateasON FROM#TEMP_BENEFIT1 T1,#TEMP_BENEFIT2 T2 WHERET1.AssessBenefitID = T2.refAssessBenefitID'
ive encounter this problem when i install the application at client side..enfect, i try it on all the PC at my office, i wouldnt encounter this problem..can anyone tell me what is possibly wrong with this?here is the code possible code effectedASPDim myDataset As Data.DataSet = New Data.DataSet Dim conn As Connection = New Connection("AbnormalControlDataConnString", "P_CreateAbnormalFormSect0") conn.AddParameter("Pending", Me.Session.Item("UserId"), Data.SqlDbType.Char, 80) conn.AddParameter("CreateBy", Me.Session.Item("UserId"), Data.SqlDbType.Char, 80) conn.executeSproc(myDataset) Me.Session.Add("RefNo", myDataset.Tables(0).Rows(0).Item(0)) conn = Nothing myDataset = Nothing gridview1.dataBind() <~~~~~~ i have this gridview bind another sproc named[P_GetAbnormalFormSect0)conn.vb Public Sub New(ByVal con As String, ByVal sprocName As String) configCon = con connectionString = System.Configuration.ConfigurationManager.ConnectionStrings(configCon).ConnectionString ' myConnection = New System.Data.SqlClient.SqlConnection(connectionString) myCommand = New System.Data.SqlClient.SqlCommand() myCommand.Connection = myConnection myCommand.CommandType = CommandType.StoredProcedure myCommand.CommandText = sprocName End Sub Public Sub AddParameter(ByVal name As String, ByVal value As String, ByVal type As SqlDbType, ByVal size As Int16) myCommand.Parameters.Add(name, type, size) myCommand.Parameters.Item(myCommand.Parameters.Count - 1).SqlValue = value End Sub Public Sub executeSproc(ByRef dataset As Data.DataSet) myConnection.Open() myDataSet = New System.Data.DataSet() myDataSet.CaseSensitive = True dataAdapter = New System.Data.SqlClient.SqlDataAdapter() dataAdapter.SelectCommand = myCommand If Not dataset Is Nothing Then dataAdapter.TableMappings.Add("asd", "UserInfo") dataAdapter.Fill(myDataSet) dataset = myDataSet myConnection.Close() Else myCommand.ExecuteNonQuery() End If End SubSprocset ANSI_NULLS ONset QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[P_GetAbnormalFormSect0] -- Add the parameters for the stored procedure here @REFNO CHAR(11) = NULLASBEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @ErrorCode int SET @ErrorCode = 0 SELECT * FROM dbo.AFStatusInfo WHERE dbo.AFStatusInfo.RefNo = @REFNO IF(@@ROWCOUNT = 0) BEGIN SET @ErrorCode = -1 END IF( @@ERROR <> 0 ) BEGIN SET @ErrorCode = @@ERROR END RETURN @ErrorCodeEND-----------------------------------------------------------------------------------------------set ANSI_NULLS ONset QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[P_CreateAbnormalFormSect0] -- Parameters for the stored procedure @Pending CHAR(80), @CreateBy CHAR(80) ASBEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- @ErrorCode : 0 No Error -- 1 No Data (Ignore when no ResultSet required) -- 2 Parameter not complete -- 3 Conflict with existing data -- Other error code please refer to @@ERROR code DECLARE @ErrorCode int SET @ErrorCode = 0 DECLARE @Id VARCHAR(11) DECLARE @Temp VARCHAR(4) SET @Temp = CAST((SELECT COUNT(*) FROM [AFStatusInfo] WHERE RefNo like ('BS200607%'))AS CHAR(3)) SET @Temp = @Temp + 1000 SET @Id = 'BS' SET @Id = @Id + CONVERT(CHAR(4),GETDATE(),20) SET @Id = @Id + CONVERT(CHAR(2),GETDATE(),10) SET @Id = @Id + SUBSTRING(@Temp,2,3) INSERT INTO [AFStatusInfo] (RefNo ,FlowStatus ,[Pending] ,[CreateBy] ,[DateCreated]) VALUES (@Id ,'New' ,@Pending ,@CreateBy ,CONVERT(CHAR(8), GETDATE(), 3)) SELECT @Id AS "RefNo" IF( @@ERROR <> 0 ) BEGIN SET @ErrorCode = @@ERROR END RETURN @ErrorCode OnError: RETURN @ErrorCodeEND----------------------------------------------------------------------------------------------------------------
Hi,Can somone please tell me why I get the error 'Must declare the scalar variable "@recCount".' when I execute this Store Procedure? ALTER PROCEDURE dbo.CountTEst AS SET NOCOUNT ON DECLARE @sql as nvarchar(100); DECLARE @recCount as int SET @SQL = 'SELECT @recCount = COUNT(*) FROM Pool' exec sp_executesql @SQL RETURN @recCount In this case I expect RETURN value = 4.I've tried various approaches, including adding an OUTPUT parameter to the exec statement, but just can't get the syntax correct. Thanks
I am not seeing the problem with this. I have a button at the bottom of this form that does this... protected void Button1_Click(object sender, EventArgs e) { SqlDataSource1.Insert(); } And the SqlDataSource code...<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:calldbConnectionString2 %>"
I’m getting the error messages: Must declare the scalar variable "@CustomerName".Must declare the scalar variable "@CustomerEmail". When using the code:sqlcommand = "UPDATE Transactions SET CustomerName=@CustomerName WHERE transid='" + thetransid.ToString().Trim() + "' "; sqlcommand += "UPDATE Transactions SET CustomerEmail=@CustomerEmail WHERE transid='" + thetransid.ToString().Trim() + "' "; cmd.Parameters.Add("@CustomerName", CustomerNameTextBox.Text); cmd.Parameters.Add("@CustomerEmail", CustomerEmailTextBox.Text); cmd = new SqlCommand(sqlcommand, conn); cmd.ExecuteNonQuery(); conn.Close();
All I want to do is run the sql server script located at http://www.data-miners.com/sql_companion.htm#downloads.
This creates some tables and uploads a series of text files into them.
When I run the script through SQL Server Express 2005 I get the error Must declare the scalar variable "@DATADIR". I suspect it's something with me putting in the wrong path.
The text files that the script needs to load into the table are located on the K drive, and I have changed the path in
declare @DATADIR varchar(128) set @DATADIR='C:gordonookdatafinal extfiles'
to
declare @DATADIR varchar(128) set @DATADIR='k: extfiles'
I suspect this is the wrong syntax that's why it's not working but I might be totally wrong.
The text file and the server are both saved on the k drive.
In my SQL Server Management Studio Express, I have a Database "testDb" that has a dbo.Inventory with a column "quantity". I executed the following sql script:
USE testDb
GO
CREATE FUNCTION AverageQuantity(@funcType varchar(20))
RETURNS numeric AS
BEGIN
DECLARE @average numeric
SELECT @average = AVG(quantity) FROM Inventory WHERE type=@funcType
RETURN @averge
END
GO
I got the following error message:
Msg 137, Level 15, State 2, Procedure AverageQuantity, Line 6
Must declare the scalar variable "@averge".
I think it was declared already in the BEGIN - END block. Please tell me why I got this error and advise me how to fix this problem.
I am trying to run a query in the data window and get the following error. How do I resolve?
query:
select distinct [Client ID] as ClientID FROM ITSTAFF.Incident WHERE [Group Name] = 'ITSTAFF' and [Client ID] is not null and [Company ID] = @[Company ID]
error:
TITLE: Microsoft Report Designer ------------------------------
An error occurred while executing the query. Must declare the scalar variable "@".
Dim EventDataSource1 As New SqlDataSource()EventDataSource1.ConnectionString =
ConfigurationManager.ConnectionStrings("ASPNETDBConnectionString").ToStringDim dssa As New DataSourceSelectArguments()Dim EventID As String = ""Dim DataView = ""Dim dt As New Data.DataTableDim conn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ASPNETDBConnectionString").ToString())Dim cmd As New Data.SqlClient.SqlCommand("SELECT EventID FROM Event WHERE ([StartDate] = @StartDate)", conn)EventDataSource1.SelectCommand = ("SELECT EventID FROM Event WHERE ([StartDate] = @StartDate)")conn.Open()dt = ((DataView)(EventDataSource1.Select(dssa))).ToTable()EventID = dt.Rows(0)(0).ToString()EventDataSource1.SelectParameters.Add("@StartDate",StartDate)EventID = cmd.ExecuteScalar()tbEventIDTest.Text = EventID
I'm attempting to create my first login form using the CreateUserWizard. I've spent this week reading up on how to create and customizing it. I want it to 1) the required user name is an email address (which seems to be working fine) and 2) having extra information inserted into a separate customized table. I now have the form working to the point where it accepts an email address for the username and it then writes that information along with the password to the aspnetdb.mdf...but i can't get the rest of the information to write to my custom table.I am getting the error "Must declare the scalara variable "@UserName" here's my .cs code:public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {
Protected Sub CreateUserWizard1_CreatedUser(ByVal sender As Object, ByVal e As System.EventArgs) Handles CreateUserWizard1.CreatedUser Dim UserNameTextBox As TextBox = DirectCast(CreateUserWizardStep2.ContentTemplateContainer.FindControl("UserName"), TextBox) Dim DataSource As SqlDataSource = DirectCast(CreateUserWizardStep2.ContentTemplateContainer.FindControl("InsertExtraInfo"), SqlDataSource)
Dim User As MembershipUser User = Membership.GetUser(UserNameTextBox.Text) Dim UserGUID
I am trying to update a field in a pre-existing record in my database. This update is supposed to happen when the protected sub entitled "PictureUpload" is called by button click. I listed the code immediately below and then I listed the error that I am getting further below that. Does anybody know what I am doing wrong and why I am getting this error? Thanks in advance and forgive my newbie ignorance!
Here is a portion of the Protected Sub that I am using in an attempt to update a field in a pre-existing record... Protected Sub PictureUpload(ByVal sender As Object, ByVal e As System.EventArgs) Dim ImageUploaded As Integer = 1 srcprofiles_BasicProperties.UpdateParameters("ImageUploaded").DefaultValue = ImageUploaded srcprofiles_BasicProperties.Update() End Sub Here is the SqlDataSource control I included on the page with (what I hope is) appropriate formatting... <asp:SqlDataSource ID="srcprofiles_BasicProperties" runat="server" ConnectionString="Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|UserProfilesDB.mdf;Integrated Security=True;User Instance=True" ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM [profiles_BasicProperties] WHERE ([UserName] = @UserName)" UpdateCommand="UPDATE [profiles_BasicProperties] SET [ImageUploaded] = @ImageUploaded WHERE ([UserName] = @UserName)"> <SelectParameters> <asp:Parameter DefaultValue="imageuploaded01" Name="UserName" Type="String" /> </SelectParameters> <UpdateParameters> <asp:Parameter Name="ImageUploaded" Type="Int32" /> </UpdateParameters></asp:SqlDataSource> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...and now the error...^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Server Error in '/PC_Dev' Application.
Must declare the scalar variable "@UserName". Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Must declare the scalar variable "@UserName".Source Error:
Line 164: Dim ImageUploaded As Integer = 1 Line 165: srcprofiles_BasicProperties.UpdateParameters("ImageUploaded").DefaultValue = ImageUploaded Line 166: srcprofiles_BasicProperties.Update() Line 167: Line 168: Source File: C:UsersMDocumentsPC_DevProfiles_BuildProfile.aspx Line: 166 Stack Trace:
Hi, I'm having trouble with this multi-statement table-valued function:
ALTER FUNCTION MakeArDetail ( -- Add the parameters for the function here @dateStart DATETIME, @dateEnd DATETIME ) RETURNS @arDetail TABLE ( Insurer VARCHAR(50), NABP INT DEFAULT 0, Claim MONEY DEFAULT 0, Payment MONEY DEFAULT 0, NumRx CHAR(7), PatientName VARCHAR(50), Paid030 MONEY DEFAULT 0, Paid3160 MONEY DEFAULT 0, Paid6190 MONEY DEFAULT 0, Paid91120 MONEY DEFAULT 0, Paid121 MONEY DEFAULT 0 ) AS BEGIN DECLARE @arTemp TABLE ( Insurer VARCHAR(50), NABP INT DEFAULT 0, Claim MONEY DEFAULT 0, Payment MONEY DEFAULT 0, NumRx CHAR(7), PatientName VARCHAR(50), Paid030 MONEY DEFAULT 0, Paid3160 MONEY DEFAULT 0, Paid6190 MONEY DEFAULT 0, Paid91120 MONEY DEFAULT 0, Paid121 MONEY DEFAULT 0 )
INSERT INTO @arTemp SELECT DISTINCT Insurer,NABP,0,0,NumRx,Patient,0,0,0,0,0 FROM Pims; UPDATE @arTemp SET Claim = (SELECT SUM(Pims.AmtReq) FROM Pims WHERE Pims.Insurer = @arTemp.Insurer AND Pims.NABP = @arTemp.NABP AND Pims.NumRx = @arTemp.NumRx );
INSERT INTO @arDetail SELECT * FROM @arTemp RETURN END GO
I get Msg 137, Level 15, State 2, Procedure MakeArDetail, Line 43 Must declare the scalar variable "@arTemp".
I don't understand why SQL thinks @arTemp is a scalar variable which has to be declared. If I don't include the UPDATE command the thing works.
I have a report that calls a stored procedure that builds a temp table and then runs a select that joins on that temp table. The only parameter I have is @Name, an optional parameter that can be filled or NULL.
I keep getting the error "An error has occurred during local report processing. An error has occurred during report processing. Query execution failed for data set. Must declare the scalar variable "@Name".
I have checked to make sure this parameter is connected to the dataset by looking at the parameter tab. I've searched on posts but haven't seen an answer. Does anyone have any idea what this could be about and how to fix it?
Hi People, i'm having some trouble with a stored proceddure used for an updat from a Formview. Error message i'm getting is Must declare the scalar variable "@CategoryID". I can't seem to work out why this is occuring and not allowing my proc to run properly. If anyone could help me that would be great :-) Here is the whole store procedure. ALTER PROCEDURE dbo.DeluxeGuideAdmin_Update @ID int,@CategoryID varchar(10), @RegionID int,@CompanyName nvarchar(25), @Email nvarchar(25),@PDFFront nvarchar(50), @PDFBack nvarchar(50),@ThumbFront nvarchar(50), @ThumbBack nvarchar(50),@Notes nvarchar(max)
AS DECLARE @SQL varchar(1000) SET @SQL = 'UPDATE DeluxeGuide SET CategoryID = @CategoryID, RegionID = @RegionID, CompanyName = @CompanyName, Email = @Email, Notes = @Notes'IF (@PDFFront IS NOT NULL) OR (@PDFFront != '') SET @SQL = @SQL + ', PDFFront = @PDFFront'IF (@PDFBack IS NOT NULL) OR (@PDFBack != '') SET @SQL = @SQL + ', PDFBack = @PDFBack'IF (@ThumbFront IS NOT NULL) OR (@ThumbFront != '') SET @SQL = @SQL + ', ThumbFront = @ThumbFront'IF (@ThumbBack IS NOT NULL) OR (@ThumbBack != '') SET @SQL = @SQL + ', ThumbBack = @ThumbBack' SET @SQL = @SQL + ' WHERE (ID = @ID)' Print '@SQL = ' + @SQLEXEC(@SQL)
I have this issue and I can not figure out the problem. I have 4 other forms from the same database using practly the same code, slight variations based on datavalidation requirements. IIS6 SQL Express 2005.
I have tried to defint eh colum for CODE as a bound filed and as a templated field. I get the same error.ASPX Page <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="MaintainBSP.aspx.cs" Inherits="MaintainBSP" Title="Maintain BSP Codes" %> <%@ MasterType VirtualPath="~/Site.master" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"><br /> <table class="mainTable" cellspacing="0" cellpadding="3" align="center"> <tr><td class="mainTableTitle">BSP Codes</td></tr> <tr><td> <table align="center"> <tr> <td><asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Center" CellPadding="3"DataKeyNames="CODE" DataMember="DefaultView" DataSourceID="SqlDataSource1" OnRowEditing="GridView1_OnRowEditing" OnRowCancelingEdit="GridView1_EndEdit" OnRowUpdated="GridView1_EndEdit"> <Columns> <asp:CommandField ShowEditButton="True" EditText="Edit" CancelText="Cancel" UpdateText="Update" HeaderStyle-CssClass="rptTblTitle" > <HeaderStyle CssClass="rptTblTitle"></HeaderStyle> </asp:CommandField> <asp:BoundField DataField="CODE" HeaderText="Code" ReadOnly="true" HeaderStyle-CssClass="rptTblTitle" /> <asp:TemplateField HeaderText="Bottle Size" SortExpression="Btl Sz"> <EditItemTemplate> <asp:TextBox ID="TextBox1" MaxLength="10" Columns="10" runat="server" Text='<%# Bind("[BOTTLE$SIZE]") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Bottle Size is a required field." Text="*" ControlToValidate="TextBox1"></asp:RequiredFieldValidator><asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Bottle size must be a number followed by 'ML' or 'L'" Text="*" ControlToValidate="TextBox1" ValidationExpression="[0-9.]+(ML|L)"></asp:RegularExpressionValidator> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("[BOTTLE$SIZE]") %>'></asp:Label> </ItemTemplate> <HeaderStyle CssClass="rptTblTitle" /> </asp:TemplateField> <asp:TemplateField HeaderText="Labeled" SortExpression="Labeled"> <EditItemTemplate> <asp:TextBox ID="TextBox2" MaxLength="1" Columns="2" runat="server" Text='<%# Bind("LABELED") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Labeled is a required field" Text="*" ControlToValidate="TextBox2"></asp:RequiredFieldValidator> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Bind("LABELED") %>'></asp:Label> </ItemTemplate> <HeaderStyle CssClass="rptTblTitle" /> </asp:TemplateField> <asp:TemplateField HeaderText="Bottles Per Case" SortExpression="Btls Per Case"> <EditItemTemplate> <asp:TextBox ID="TextBox3" Columns="4" runat="server" Text='<%# Bind("[BOTTLES$PER$CASE]") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Bottles per case must be a whole number." Text="*" ControlToValidate="TextBox3"></asp:RequiredFieldValidator> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Bind("[BOTTLES$PER$CASE]") %>'></asp:Label> </ItemTemplate> <HeaderStyle CssClass="rptTblTitle" /> </asp:TemplateField> <asp:TemplateField HeaderText="Liters Per Case" SortExpression="Ltrs Per Case"> <EditItemTemplate> <asp:TextBox ID="TextBox4" MaxLength="8" Columns="8" runat="server" Text='<%# Bind("[LITERS$PER$CASE]") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Liters per case must be a number." ControlToValidate="TextBox4" Text="*"></asp:RequiredFieldValidator> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label4" runat="server" Text='<%# Bind("[LITERS$PER$CASE]") %>'></asp:Label> </ItemTemplate> <HeaderStyle CssClass="rptTblTitle" /> </asp:TemplateField> <asp:CommandField ShowDeleteButton="True" DeleteText="Delete" HeaderStyle-CssClass="rptTblTitle" > <HeaderStyle CssClass="rptTblTitle"></HeaderStyle> </asp:CommandField> </Columns>
Im trying to insert some values into a table but i get the following error: System.Data.SqlClient.SqlException: Must declare the scalar variable "@username". the strange thing is that the variable username is declared at the beginning and acording to my debugger the variable username has a value (that it gets from a textbox when a button is pressed). Here is my code so please feel free to point out what im doing wrong. Im a beginner to using asp.net.1 protected void ButtonSubmit_Click(object sender, EventArgs e) 2 { 3 string @username = TextBoxUsername.Text; 4 string @company = TextBoxCompany.Text; 5 string @password = TextBoxPassword.Text; 6 string @mail = TextBoxMail.Text; 7 string @adr = TextBoxAdr.Text; 8 string @phone = TextBoxPhone.Text; 9 string @contact = TextBoxContact.Text; 10 string myConnectionString; 11 12 myConnectionString = @"Data Source=.SQLEXPRESS;AttachDbFilename=C:UsersalhoDocumentsIntrapointWebApp_DataIntrapoint.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; 13 14 SqlConnection myConnection = new SqlConnection(myConnectionString); 15 string myInsertQuery = "INSERT INTO company (username, password, company, mail, adr, phone, contact) Values(@username, @password, @company, @mail, @adr, @phone, @contact)"; 16 SqlCommand myCommand = new SqlCommand(myInsertQuery); 17 myCommand.Connection = myConnection; 18 myConnection.Open(); 19 myCommand.ExecuteNonQuery(); 20 myCommand.Connection.Close(); 21 22 }
Hi, Can anybody help me with this, I've got a simple program to add a new record to a table (2 items ID - Integer and Program - String) that matches all examples I can find, but when I run it I get the error : Must declare the scalar variable "@BookMarkArrayA". when it reaches the .insert command, I've tried using a local variable temp in place of the array element and .ToString , but still get the same error This is the code : Public Sub NewCustomer() Dim temp As String = " " Dim ID As Integer = 1 'Restore the array from the view state BookMarkArrayA = Me.ViewState("BookMarkArrayA")
temp = BookMarkArrayA(6) Dim Customer As SqlDataSource = New SqlDataSource()