.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

How to insert variables inside a query?

Posted By:      Posted Date: April 14, 2011    Points: 0   Category :ASP.Net



i've facing this problem in my program..


Dim a As Integer = 1
Do Until a = 12
            Dim con As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
            Dim cmd As System.Data.SqlClient.SqlCommand = New SqlCommand

                cmd.CommandText = "update it_report set network=(select count(*) from tbl_form_it_service where usercase in ('NETWK') and datepart(year,reportdatetime)= '2010'  and datepart(month,reportdatetime) = " & a & ") where year=2010 and month= " & month & "" 
                cmd.Connection = con


                DataGrid1.DataSource = cmd.ExecuteReader()


            Catch ex As Exception
                Message.Text = "Error! " & ex.ToString
                Exit Sub
            End Try

            a = a + 1


how can i insert  loop statement variable into the query?? and how to insert textfield id in the query also? 
2010 will be textfield value.

help me,

View Complete Post

More Related Resource Links

INSERT Statement Inside a UDF?

I am using SQL Server 2005.  I know you can not put INSERT or UPDATE statements in a UDF.  I am looking for an alternative to getting the end result I need since this call has to go at a specific point in the code or it will never work.  I have a UDF which packs smaller boxes into a bigger box efficiently.  The UDF typically runs and creates as many bigger boxes as possible until all smaller boxes are used and then it returns a TABLE variable back to a stored procedure.  I need to insert a record into a new table at the point where each bigger box is full before it moves on to the next bigger box.  There is only a couple alternatives I can see but don't really know if each is possible.  I am open to an ideas: 1. Call a stored procedure from the UDF which executes the insert statement 2. Using EXECUTE to perform the insert statement 3. Re-write the UDF as a stored procedure.  It must be able to table two inputs and return a table which can be unioned with two other views. 4. Anything Else UPDATE: Scratch idea #1 since it says I can only call other functions or extended stored procedures UPDATE: Scratch idea #2 as it did not work

INSERT statement with OUTPUT clause, referencing outer query columns

I have a problem to solve and I have run into what appears to be a limitation of TSQL.  I have looked around and did not find much on this subject, so I apologize if this duplicates another post.  I am using SQL Server 2008. From what I have read on BOL, when you are performing a DELETE or UPDATE statement, you can reference unaffected columns from the outer query in the OUTPUT clause, but this is apparently not allowed in an INSERT statement. I am working on a process that will create new copies of existing records - essentially, the user can create a whole new copy of a set of records, and the process requires that I track both what the original PK values were and the corresponding PK values for the new rows. This example will hopefully spell out my problem.  This script shows two tables, [Primary_Object] and [Secondary_Object].  Not shown here are multiple tables that rely on [Secondary_Table], which is why I have to be able to track this info. This first script shows the setup of the tables involved and the data involved: /* create test data */ create table primary_object ( primary_object_id int identity(1,1), parent_object_id int, name char(1)) create table secondary_object ( secondary_object_id int identity, primary_object_id int, amount money) insert into primary_object (parent_object_id, name) select 0, 'A' insert into secon

Insert Into SQL Server inside a For Each - Next Statement

I have the following code to For each Item in the file uploader, Insert Into database.... but It doesnt work in the For Each Statement but if i take it out of the For Each statement it works.   For Each item As AttachmentItem In Attachments1.Items            Dim objConn2 As New SqlConnection("Data Source=XXX")            objConn2.Open()            Dim objCmd2 As New SqlCommand("INSERT INTO clientport (name, event, date1, username, password, path)" & "VALUES (@name, @event, @date1, @username, @password, @path)", objConn2)                                 objCmd2.Parameters.AddWithValue("@name", clientname.Text)            objCmd2.Parameters.AddWithValue("@event", [event].Text)            objCmd2.Parameters.AddWithValue("@date1", [date].Text)            objCmd2.Parameters.AddWithValue("@username", username.Text)  &nbs

insert query from ms SQL server into a mysql linked server

INSERT into openquery(dbserver1MySQL,'select * from graham.lookup_in_table') select * from NavteqAPAC.dbo.Admin_Names   is giving me the following error! Please help me   OLE DB provider "MSDASQL" for linked server "dbserver1MySQL" returned message "[MySQL][ODBC 5.1 Driver][mysqld-5.1.49-community]Commands out of sync; you can't run this command now". Msg 7343, Level 16, State 2, Line 1 The OLE DB provider "MSDASQL" for linked server "dbserver1MySQL" could not INSERT INTO table "[MSDASQL]".

SSIS Query requiring two variables

I have a query in which I need to use two variables. How do I implement this in SQL task editor for the intake of two variables????

insert query with subquery

Hello, I have 2 tables, one fact table (FeitDienstDagen) which contains employments, and a reference/dimension table, vDimMedewerker,  which contains a history of employees and their departments. IN the fact table I want to insert the correct WerkID from vDimMedewerker. So the employeeID (ms120_obj) must be same,  and the DienstDag_KEY (int date Key) must be greater then or equal to  the first werk_start_KEY (int date key) for that employee,  Ordered descendant. How to do that? Her my query, but it doesn't do the job :-) USE TEAMSOFT_TBSDB GO DELETE FROM dbo.FeitDienstdagen GO INSERT INTO [TEAMSOFT_TBSDB].[dbo].[FeitDienstdagen]            ([DienstverbandID]            ,[Deeltijdfactor]            ,[DienstDag_KEY]            ,[MutatieID]            ,[DienstverbandStart]            ,[DienstverbandEind]            ,[UrenWeek]            ,[Contracturen]            ,[UrenDag]     

DropDownList inside FormView Insert Template

Hi, I am trying to change the textboxes in the FormView insert template to dropdownlists but they keep setting the parameters to null.   Here's what I have:  <asp:DropDownList ID="ddlYearOfQualification" SelectedValue='<%# Bind("YearOfQualification") %>' runat="server"> </asp:DropDownList> In Page_Load CType(frmSurvey.FindControl("ddlYearOfQualification"), DropDownList).Items.Add(New ListItem("2010", "2010"))CType(frmSurvey.FindControl("ddlYearOfQualification"), DropDownList).Items.Add(New ListItem("2009", "2009"))   and in the SqlDataSource InsertCommand="INSERT INTO [tblSurvey] (... [YearOfQualification] ...) VALUES ( ... @YearOfQualification ... ) And in insert parameters: <asp:Parameter Name="YearOfQualification" Type="Int16" /> And the insert fails with YearOfQualification as null. If I sue the standard textbox: <asp:TextBox ID="YearOfQualificationTextBox" runat="server"                 Text='<%# Bind("YearOfQualification") %>' /> It works.   Any ideas? Many thanks in advance.

SharePoint Dataview Insert New Mode - Defaulting a Required Column to a Query String Parameter Valu

I've got a SharePoint DataView with an insert button. there is a required lookup column I want to default to the value of Querystring Value during new mode.  Can I do this in the generated code below? I tried replacing @ApplicantId with @QSApplicantID.. and  tried string(@QSApplicantID) too.. no luck gave me an error: The data source control failed to execute the insert command. Could it be that QSApplicantID (which I've used in my DataView Datasource filter with no problem) is not available during the insert? I think I can do what I want in Javascript but was hoping I could instead right in the XSL markup. *my query string parameter**     ParameterBinding Name="QSApplicantID" Location="QueryString(ID)" DefaultValue="2222222"/ **the new form** SharePoint:FormField runat="server" id="ff4{$Pos}" ControlMode="New" FieldName="ApplicantId" __designer:bind="{ddwrt:DataBind('i',concat('ff4',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@ApplicantId')}" / **the link** a href="javascript: {ddwrt:GenFireServerEvent('__cancel;dvt_1_form_insertmode={1}')}">Insert</a Thanks for any help or information!

Setting SharePoint 2010 Form Fields Using Query String Variables


Hi All,

I have a requirement to populate sharepoint form field value with query string while uploading document to document library.

While uploading the document to document library, I want to populate claim number available from query string in a pop up page i.e in my case EditForm.aspx, Located at http://servername:port/sitename/documentlibraryname/forms/EditForm.aspx.

Additional Information:

  • Created document library and added custom columns like claim number etc..
  • Created a view to filter uploaded documents as per claim number.

Server Details:

  • Windows Server 2008 R2
  • SharePoint 2010
  • SQL Server 2008 R2

I have written javascript for the same, but not sure where exactly to add the code in EditForm.aspx page.

Any help on this would be greatly appreciated.

Thanking you in advacne.



SQL Query Help - Aggregate Functions Across Several Variables


I have a table that looks like this….


Size                  BillCode           Qty      Weight

4                      A                     3          230

4                      B  &nbs

DropDownLists inside Detailsview INSERT cant get to work.



I'm having a DetailsView which has two DropDownList's inside so I should be able to pick 2 values for the field from DDL instead of writing something for it. But I cant get it to Insert any new values to my Database...

Can anyone help me with this? I'm pasting my code and table details here below.

<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
        CellPadding="4" DataKeyNames="SignUpKey" DataSourceID="LinqDataSource1"
        DefaultMode="Insert" ForeColor="#333333" GridLines="None" Height="50px"
        Width="125px" oniteminserted="DetailsView1_ItemInserted"
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

How to write SQL Insert into query using LINQ


How I can write following SQL query using LINQ. There is no default constraint define for the ID column so we have explicitly pass the NEWID().

I want to replicate the products of a company to another company.

Insert Into Products
Select NEWID() AS ProductID, ProductName, CompanyID = @DestinationID, ProductCategoryID From Products Where CompanyID = @SourceID

Also once I get these result how can I use InsertAllOnSubmit to insert all the records at once without looping it.

If not Exist Insert Query


Hi I have the syntax for the following query but dont understand why  UsePrimayKeyHere = 'UsePrimaryKeyHere' is in Where clause?


(SELECT 1 FROM [EligStaging].[Uaqa].[CrosswalkTableNameHere]

 WHERE [UsePrimaryKeyHere] = UsePrimaryKeyHere')


Insert Column Limit from XML? The query processor ran out of stack space during query optimization e


I get the following error:

Msg 8621, Level 17, State 2, Procedure ProcessFliteTracWorkingXML_FTPax, Line 348
The query processor ran out of stack space during query optimization. Please simplify the query.

I have looked at this KB fix, but we are a newer version then in that article:

Also found this post with a similiar issue, but no solution:

Before I call Microsoft Support I thought I would try here first.

I am trying to run a stored proc that basically needs to parse xml messages coming from an outside datasource.  We are using SQL Server 2005 SP3 (9.00.4053.00 SP3 Standard Edition).  This datasource is an old pervasived database with not the best data model.  So what we wanted to do was pull the raw data as is into a staging table and then convert it to a better data model in our ODS.  There are around 300 columns in this table and I have a generic process that pulls the rows out and converts to XML and saves to a working table (this

How to insert a button or link inside a discussion forum


When users are inside the discussion list they want a link or button to return to the home page. How do I insert this on the discussion page?

cindi bethel carmona

Insert Query - Help Please!


Hello, I am attempting to do an insert query on a webpage for a simple member registration form I have created in vs2010. I have done this type of thing before without problem using an access database, but now I'm using a sqlexpress db created from within vs2010. This is the screenshot of my insert query:

Insert Query

Now, when I execute this query in the form, I get an error that says:

Must declare the scalar variable "@FirstName".

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 "@FirstName".

Source Error: 

Error on Insert query


I'm getting an error on the following query that I don't quite understand:


[DB names changed to keep the associated apps at least somewhat anonymous :)   ]

insert into DB1.dbo.CUST

select 'T', cast(CustomerID as varchar(15)),
DB2.dbo.getcustomerattributevalue(CustomerId, 'FirstName') + ' ' + DB2.dbo.getcustomerattributevalue(CustomerId, 'LastName'),
 'DL', 'DCH',
RegistrationDate, 'USD' 
from DB2.dbo.Customer where CustomerID = 42


The error that I'm getting is the following:

Msg 8114, Level 16, State 5, Line 1

Error converting data type varc

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend