Inserting Variables Into A Query Using SqlDataSource
Jan 4, 2008
Hi all,
I was wondering if anyone can help me figure out how to insert a
variable into a query using Visual Studio 2005 with the SqlDataSource
control. I cant seem to be able to enter a var into the query
parameters.
this is my SqlDataSource:
<asp: SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:imLookinLikeConnectionString
%>"
DeleteCommand="DELETE FROM [tblDiaryEntries] WHERE [DiaryEntryID] = @DiaryEntryID"
SelectCommand="SELECT tblDiaryEntries.DiaryEntryID,
tblDiaryEntries.EntryDate, tblDiaryEntries.Subject,
tblDiaryEntries.DiaryEntry, aspnet_Users.UserName FROM tblDiaryEntries
INNER JOIN aspnet_Users ON tblDiaryEntries.UserID = aspnet_Users.UserId
WHERE UserName=@UserName ORDER BY tblDiaryEntries.EntryDate DESC"
UpdateCommand="UPDATE [tblDiaryEntries] SET [DiaryEntry] = @DiaryEntry,
[EntryDate] = @EntryDate, [Subject] = @Subject WHERE [DiaryEntryID] =
@DiaryEntryID" InsertCommand="INSERT INTO tblDiaryEntries(UserID,
EntryDate, Subject, DiaryEntry) VALUES (@UserId, GETDATE(), @Subject,
@DiaryEntry)">
<DeleteParameters>
<asp: Parameter Name="DiaryEntryID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp: Parameter Name="DiaryEntry" Type="String" />
<asp: Parameter Name="EntryDate" Type="String" />
<asp: Parameter Name="Subject" Type="String" />
<asp: Parameter Name="DiaryEntryID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp: Parameter Name="DiaryEntry" Type="String" />
<asp: Parameter Name="EntryDate" Type="String" />
<asp: Parameter Name="Subject" Type="String" />
<asp: ProfileParameter DefaultValue="Anonymous" Name="UserName" PropertyName="UserName" />
<asp: Parameter Name="UserId" />
</InsertParameters>
<SelectParameters>
<asp: ProfileParameter DefaultValue="Anonymous" Name="UserName" PropertyName="UserName" />
</SelectParameters>
</asp: SqlDataSource>
What I want to do is to tell the SqlDataSource that @UserName = this.User.Identity.Name, but I only know how to do that in
code-behind, not sure how to insert it into the code above.Any ideas?
View 3 Replies
ADVERTISEMENT
Aug 19, 2007
I want to make a sqldatasource to insert data ito a table with values from textfields page. I want to use the sqldatasource programically (not bind it to a formcontrol).
I drag a sqldatasource from the toolbox to the design surface and start configuring the datasource. I spesify a custom sql statement, select the "Insert" tab and insert the table I want to store into the builder. Then I select the fields and the values (parameters from tue textfields. I test it with the "Execute query" button and the results is stored in the table. (everything seems ok) I press the "OK" button but both the "Next" and "Finish" buttons are dissabled, o I can not store the query.
What is going wrong. Can someone please help me ?
Tom Knardahl
View 2 Replies
View Related
Mar 2, 2007
hi, i have a simple question, it sounds a bit silly but i have not been able to figure it out. i want to be able to pass variable from code behind to an sqldatasource, i have been using session varibles, but is now becoming a bit messy as i have over 30 session viarables. i wanted to find out if i can create a private variable in the code behind, and access the value.
Does anyone know how i can do this, i'm not sure if it is possible, if it is what paramater i can use to access it.
Or if anyone has any better ideas to create variables for one page, so i can pass it to sqldatasource, would be great..
many thanks
manish
View 4 Replies
View Related
Feb 18, 2008
If anyone can see what else I need to insert the stuff below into my database, I'd really appreciate it. I get intellisense, but also this error: Cannot insert the value NULL into column 'UserID' strUserName = cuwCreate.UserName.ToString
strUserID = Membership.GetUser(strUserName).ProviderUserKey.ToString()
Session("NewUserName") = strUserName
Session("NewUserID") = strUserID <asp:SqlDataSource ID="srcCreateUser" runat="server" ConnectionString="<%$ ConnectionStrings:webConn %>"
InsertCommand="sp_CreateUser" InsertCommandType="StoredProcedure" SelectCommand="sp_CreateUser"
SelectCommandType="StoredProcedure" UpdateCommand="sp_CreateUser" UpdateCommandType="StoredProcedure">
<SelectParameters>
<asp:SessionParameter Name="UserID" SessionField="NewUserID" Type="String" />
<asp:ControlParameter ControlID="UserName" DefaultValue="" Name="UserName" PropertyName="Text"
Type="String" />
<asp:ControlParameter ControlID="Email" Name="Email" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="txtFirstName" Name="FirstName" PropertyName="Text"
Type="String" />
<asp:ControlParameter ControlID="txtLastName" Name="LastName" PropertyName="Text"
Type="String" />
<asp:ControlParameter ControlID="txtTeacher" Name="Teacher" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="txtGradYr" Name="GradYr" PropertyName="Text" Type="Int32" />
</SelectParameters>
<InsertParameters>
<asp:SessionParameter Name="UserID" SessionField="NewUserID" Type="String" />
<asp:Parameter Name="UserName" Type="String" />
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="Teacher" Type="String" />
<asp:Parameter Name="GradYr" Type="Int32" />
</InsertParameters>
</asp:SqlDataSource>Dim obj As SqlDataSource = cuwRegister.ContentTemplateContainer.FindControl("srcCreateUser")
obj.Insert()
View 17 Replies
View Related
Feb 29, 2008
I’ve got the following piece of ASP code, which updated a
table through the standard edit/update command filed options.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$
ConnectionStrings:CAT_SYSTEMConnectionString %>"
OldValuesParameterFormatString="original_{0}"
SelectCommand="sp_diplomaViewQualifications"
UpdateCommand="UPDATE
PsnQualifications SET quantity=@quantity WHERE rowstatus=1 and
qualId=@original_qualId"
DeleteCommand="UPDATE
PsnQualifications SET rowStatus=0, lastUpdateOn=getdate(), lastUpdateBy=@createdBy
WHERE rowstatus=1 and qualId=@original_qualId"
SelectCommandType="StoredProcedure">
<UpdateParameters>
<asp:Parameter Name="original_qualId"
/>
<asp:Parameter Name="quantity"
/>
</UpdateParameters>
<DeleteParameters>
<asp:Parameter Name="original_qualId"
/>
<asp:Parameter Name="createdBy" DefaultValue="TEST"/>
</DeleteParameters>
<SelectParameters>
<asp:Parameter Name="masterKey"
/>
</SelectParameters>
</asp:SqlDataSource>
My problem is that I need to pass the contents
of the VB variable ‘createdBy’ into the DeleteParameters option.
This is defined in the code as: Dim createdBy As String = getUserLoginName(Me.Page)
How do I pass this into the update and/or delete part
of the command field on the ASP page?
View 3 Replies
View Related
Mar 11, 2007
Hi all, first post, and I am desperate.
I have a SqlDataSource with a Select, Update and Delete command. From what I understand, scalar variables should be read automatically from the GridView's BoundField columns when it executes a command on it. Here is my code:
<asp:GridView
ID="teamGrid"
EmptyDataText="n/a"
DataKeyNames="TeamId"
AutoGenerateColumns="false"
DataSourceID="teamSource"
OnRowEditing="validateEdit"
OnRowDeleting="validateDelete"
runat="server">
<Columns>
<asp:CheckBoxField DataField="TeamApproved" HeaderText="Approved" />
<asp:BoundField DataField="TeamName" HeaderText="Team Name" />
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label runat="server"><%# Eval("City") %></asp:Label>, <asp:Label runat="server"><%# Eval("ProvinceCode") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RequestedDivision" HeaderText="Division Req." ControlStyle-Width="60px" />
<asp:BoundField DataField="DivisionCode" HeaderText="Assigned Division" ControlStyle-Width="60px" ConvertEmptyStringToNull="true" NullDisplayText="n/a" />
<asp:BoundField DataField="DivisionNumber" HeaderText="Division Number" ControlStyle-Width="60px" ConvertEmptyStringToNull="true" NullDisplayText="n/a" />
<asp:BoundField DataField="Password" HeaderText="Password" ConvertEmptyStringToNull="true" NullDisplayText="n/a" />
<asp:CheckBoxField DataField="Paid" HeaderText="Paid" />
<asp:HyperLinkField Text="view players" ItemStyle-Width="70px" ItemStyle-HorizontalAlign="Center" DataNavigateUrlFields="TeamId" DataNavigateUrlFormatString="viewTeamPlayers.aspx?teamId={0}" ShowHeader="false" />
<asp:CommandField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="30px" ButtonType="Link" EditText="edit" ShowEditButton="true" ShowHeader="false" />
<asp:TemplateField ShowHeader="False" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="30px">
<ItemTemplate>
<asp:LinkButton runat="server" CausesValidation="False" CommandName="Delete" OnClientClick='return confirm("Deleting this team will also delete the players. Are you sure you wish to continue?");' Text="delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource
ID="teamSource"
ConnectionString="<%$ ConnectionStrings:MB %>"
SelectCommand="SELECT TeamId, TeamName, ProvinceCode, City, DivisionCode, DivisionNumber, TeamApproved, RequestedDivision, Paid, Password, CaptainId, Player2Id, Player3Id, Player4Id FROM [Team]"
UpdateCommand="UPDATE [Team] SET TeamName = @TeamName, DivisionCode = @DivisionCode, DivisionNumber = @DivisionNumber, TeamApproved = @TeamApproved, Paid = @Paid, Password = @Password WHERE TeamId = @TeamId"
runat="server" />
</form>
I apologize for the way the code is put in, the code thing cut off a lot of the text! The problem I'm getting is, when the 'Update' button is hit, I get the error: Must declare the variable '@TeamId'.
I've tried putting "Update Parameters", that takes away the error, but the row does not update. I've browsed the internet and saw the same problems in lots of areas, but either a) none of the solutions work for me, or b) they don't really apply to my case.
I'm using ASP .NET 2.0, and (obviously) C#. SQL Server database.
Any help is greatly appreciated. Thanks in advance,
- Branden
View 2 Replies
View Related
Apr 14, 2008
Is there any way I can use a variable from my code behind file in the UpdateCommand of a sqlDataSource? I have tried
<%$ strUserGuid %>and<% strUserGuid %>
any help appreciated.Thanks
Dave
View 2 Replies
View Related
Oct 6, 2006
I set up a Sqldatasource control in 2.0 and I can retrieve data through a SQL Server connection from a stored procedure. My problem is when I set up the insert command object through the wizard for the Sqldatasource control with another stored procedure for inserting data and call the insert method of my Sqldatasource object i get nothing not even an error it just goes through the code like nothing was wrong and I don't get anything inserted. I don't know if this could be a problem but one of the parameters in the stored procedure is declared like this: @return tinyint output. I don't know how the Sqldatasource accounts for return parameters. Here is the code for the insert for the Sqldatasource object.<asp:SqlDataSource ID="sdsMain" runat="server" ConnectionString="<%$ ConnectionStrings:SN_CUSTOMERConnectionString %>"InsertCommand="uspSNOrder_Promo_Live" InsertCommandType="StoredProcedure" SelectCommand="uspOPFillPromo"SelectCommandType="StoredProcedure"><InsertParameters><asp:ControlParameter ControlID="ddlPromo" Name="promoid" PropertyName="SelectedValue"Type="Int32" /><asp:Parameter DefaultValue="1" Name="datasourceid" Type="Int32" /><asp:Parameter DefaultValue="0" Name="datasourcekey" Type="String" /><asp:Parameter DefaultValue="9" Name="salesroomid" Type="Int32" /><asp:Parameter DefaultValue="9999" Name="userid" Type="Int32" /><asp:ControlParameter ControlID="txtFName" DefaultValue="" Name="firstname" PropertyName="Text"Type="String" /><asp:ControlParameter ControlID="txtLName" Name="lastname" PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="txtAddress" Name="address" PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="txtCity" Name="city" PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="txtState" Name="state" PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="txtZip" Name="zip" PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="txtPhone" Name="phone" PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="txtEmail" Name="email" PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="ddlStatus" Name="status" PropertyName="SelectedValue"Type="Int32" /><asp:Parameter DefaultValue="0" Direction="InputOutput" Name="return" Type="Byte" /></InsertParameters></asp:SqlDataSource>Thanks in advance
View 1 Replies
View Related
Apr 12, 2007
Greetings,
When using Inserting event of SqlDataSource ASP.NET gives me an error when I reference InsertParameter by Name
An SqlParameter with ParameterName 'CreatedByEmployeeId' is not contained by this SqlParameterCollection.
However, when I reference parameter by index everything works.
Is this a bug or I'm doing something wrong?
Here's the code:
<asp:SqlDataSource ID="dsRole" runat="server" ConnectionString="<%$ ConnectionStrings:SecurityConnectionString %>" DeleteCommand="spDeleteRole" InsertCommand="spAddRole" SelectCommand="spGetRole" UpdateCommand="spUpdateRole" DeleteCommandType="StoredProcedure" InsertCommandType="StoredProcedure" SelectCommandType="StoredProcedure" UpdateCommandType="StoredProcedure">
<DeleteParameters>
<asp:Parameter Name="RoleId" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="RoleId" Type="Int32" />
<asp:Parameter Name="RoleName" Type="String" />
<asp:Parameter Name="RoleDescription" Type="String" />
<asp:Parameter Name="UpdatedByEmployeeId" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="RoleName" Type="String" />
<asp:Parameter Name="RoleDescription" Type="String" />
<asp:Parameter Name="CreatedByEmployeeId" Type="Int32" />
</InsertParameters>
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="RoleId" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
When using parameter name, I get an error:
Protected Sub dsRole_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles dsRole.Inserting
e.Command.Parameters("CreatedByEmployeeId").Value = Internal.Security.GetEmployeeIdFromCookie(Page.Request.Cookies)
End Sub
When using index instead of name, there's no problem:
Protected Sub dsRole_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles dsRole.Inserting
e.Command.Parameters(2).Value = Internal.Security.GetEmployeeIdFromCookie(Page.Request.Cookies)
End Sub
View 2 Replies
View Related
Oct 5, 2006
Hi,
I need a resolution of the following issue:
Following SQL is to be inserted in an audit table :
INSERT INTO GLOBAL_VARIABLE_LOAD
([LOAD_ID]
,[LOAD_STATUS]
,[START_TIME]
,[END_TIME])
VALUES
(@P_LOAD_ID
,@P_LOAD_STATUS
,@P_START_TIME
,@P_END_TIME)
@P_LOAD_ID, @P_LOAD_STATUS, @P_START_TIME, @P_END_TIME are the 4 parameters mapped to global variables (At package Level) which store values mapped in a previous SQL Task in my control flow.
Following Error Message is thrown on executing the SQL Task:
Invalid object name 'GLOBAL_VARIABLE_LOAD'.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Can anyone guide me as to how should I go about saving values in global variables and inserting them in a table.
Thanks in advance.
Regards,
Aman
View 4 Replies
View Related
Jun 26, 2006
Hi, I have created a website and I have a web form, I need to capture data and calculate fields and then insert the calculated field including the data into a sqlserver database. I created a store procedure and the parameters for the txt boxes is working fine. But the calculated fieldds are not getting inserted. Can someone please help? the code for insert is below: For the calculated field, I used txtboxes which "hold" the calculated field in the submit button event. I also tried using query string field
like this: but that did not work either. Help will be very much appreciated.
<asp:QueryStringParameter DefaultValue="1" Name="totlabchg" QueryStringField="laborcharge"
Type="Decimal" />__________________
<InsertParameters>
<asp:FormParameter DefaultValue="0" FormField="txtaccount" Name="ActNumber" Type="String" />
<asp:FormParameter DefaultValue="0" FormField="txtmeter" Name="MeterNumber" Type="String" />
<asp:FormParameter DefaultValue="0" FormField="txtdov" Name="VisitDate" Type="DateTime" />
<asp:FormParameter DefaultValue="" FormField="txtsvadd" Name="SvAdd" Type="String" />
<asp:Parameter Name="TampId2" Type="Int32" />
<asp:Parameter DefaultValue="64.44" Name="charge1" Type="Decimal" />
<asp:FormParameter FormField="txtq1" Name="quantity1" Type="Int32" />
<asp:QueryStringParameter DefaultValue="1" Name="subtotal1" QueryStringField="sub1" Type="Decimal" />
<asp:FormParameter DefaultValue="1" FormField="txtpeople" Name="labor" Type="Int32" />
<asp:FormParameter DefaultValue="1" FormField="txthrs" Name="laborhrs" Type="Decimal" />
<asp:FormParameter DefaultValue="1" FormField="txttotlab" Name="totlabchg" Type="Decimal" />
<asp:Parameter DefaultValue="300.00" Name="flatrate" Type="Decimal" />
<asp:FormParameter DefaultValue="1" FormField="txttotalcharge" Name="totalcharge"
Type="Decimal" />
<asp:FormParameter DefaultValue="1" FormField="txtgrandtotal" Name="grandtotal" Type="Decimal" />
<asp:Parameter Direction="ReturnValue" Name="RETURN_VALUE" Type="Int32" />
</InsertParameters>
Thanks.
View 1 Replies
View Related
Sep 21, 2006
Hi Guys. I am trying to insert the date as the default value into the DatePosted parameter in the sqldatasource object. I have put have the following below but it doesn't work. I have also tried <asp:Parameter Name="DatePosted" Type="DateTime" DefaultValue="<%= Date.Now %>" /> <asp:Parameter Name="DatePosted" Type="DateTime" DefaultValue="<%= now() %>" /> I know the solution is probably simple and I look like an idiot, but excuse me because I am very knew and fragile at this lol... any help would be great :). Mike.
View 7 Replies
View Related
Feb 9, 2006
I have a database with columnsuserOwnListsuserID uniqueidentifieruserName nvarchar100userList nvrachar100createdDateI
have created successfully a gridview controller to edit these values in
database. The Gridview data is populated by SqlDataSource.I
have also created a EmptyDataTemplate and created a form into it.
There is only one textBox and submit button to create the First entry
to userOwnLists -table.Now I collect the value from EmptyDataTemplate textbox with id userList1 and create a codebehind logic for the submitbutton.protected void Button2_Click(object sender, EventArgs e) { TextBox listName = (TextBox)this.FindControl("listName1", GridView1.Controls);SqlDataSource1.InsertParameters["userId"].DefaultValue = Membership.GetUser().ProviderUserKey; SqlDataSource1.InsertParameters["userName"].DefaultValue = Membership.GetUser().UserName.ToString(); SqlDataSource1.InsertParameters["listName"].DefaultValue = listName.Text; SqlDataSource1.InsertParameters["createdDate"].DefaultValue = DateTime.Now.ToString(); SqlDataSource1.Insert(); }The problem is now that I get error: Exception Details: System.Data.SqlClient.SqlException:
Implicit conversion from data type sql_variant to uniqueidentifier is
not allowed. Use the CONVERT function to run this query.OK. So I Googled a bit and found this:http://scottonwriting.net/sowblog/posts/4690.aspxMy Question is: How do I convert userId so I can insert it to database successfully?This does not work:String userId = Membership.GetUser().ProviderUserKey.ToString(); SqlDataSource1.InsertParameters["userId"].DefaultValue = Convert.ToString(userId);
View 2 Replies
View Related
Oct 25, 2006
Hi, it is few days I posted here my question, but received no answer. Maybe the problem is just my problem, maybe I put my question some strange way. OK, I try to put it again, more simply. I have few textboxes, their values I need to transport to database. I set SqlDataSource, parameters... and used SqlDataSource.Insert() method. I got NULL values in the database's record. So I tried find problem by using Microsoft's sample code from address http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.insert.aspx. After some changes I tried that code and everything went well, data were put into database. Next step was to separate code beside and structure of page to two separate files followed by new test. Good again, data were delivered to database. Next step: to use MasterPage, very simple, just with one ContentPlaceHolder. After this step the program stoped to deliver data to database and delivers only NULLs to new record. It is exactly the same problem which I have found in my application. The functionless code is here:http://forums.asp.net/thread/1437716.aspx I cannot find any answer this problem on forums worldwide. I cannot believe it is only my problem. I compared html code of two generated pages - with maserPage and without. There are differentions in code in ids' of input fields generated by NET.Framework:Without masterpage:<input name="NazevBox" type="text" id="NazevBox" /><span id="RequiredFieldValidator1" style='color:Red;visibility:hidden;'>Please enter a company name.</span><p><input name="CodeBox" type="text" id="CodeBox" /><span id="RequiredFieldValidator2" style='color:Red;visibility:hidden;'>Please enter a phone number.</span><p><input type="submit" name="Button1" value="Insert New Shipper" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("Button1", "", true, "", "", false, false))" id="Button1" /> With masterpage:<input name="ctl00$Obsah$NazevBox" type="text" id="ctl00_Obsah_NazevBox" /><span id="ctl00_Obsah_RequiredFieldValidator1" style='color:Red;visibility:hidden;'>Please enter a company name.</span><p><input name="ctl00$Obsah$CodeBox" type="text" id="ctl00_Obsah_CodeBox" /><span id="ctl00_Obsah_RequiredFieldValidator2" style='color:Red;visibility:hidden;'>Please enter a phone number.</span><p><input type="submit" name="ctl00$Obsah$Button1" value="Insert New Shipper" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$Obsah$Button1", "", true, "", "", false, false))" id="ctl00_Obsah_Button1" />In second case ids' of input fields have different names, but I hope it is inner business of NET.Framework.There must be something I haven't noticed, maybe NET's bug, maybe my own. Thanks for any suggestion.
View 2 Replies
View Related
Dec 6, 2006
I'm getting error:
String was not recognized as a valid DateTime.
my insert parameter:
<asp:Parameter Name="LastModified" Type="DateTime" DefaultValue= "<%=DateTime.Now.ToString() %>"
my insert command:
InsertCommand="INSERT INTO [Product] ([Enabled], [ProductCode], [ProductName], [ProductAlias], [CarrierId], [DfltPlanId], [DoubleRating], [DoubleRateProductId], [ConnCharges], [StartDate], [EndDate], [Contracted], [BaseProductId], [LastModified], [LastUser]) VALUES (@Enabled, @ProductCode, @ProductName, @ProductAlias, @CarrierId, @DfltPlanId, @DoubleRating, @DoubleRateProductId, @ConnCharges, @StartDate, @EndDate, @Contracted, @BaseProductId, @LastModified, @LastUser)"
LastModified is a datetime field.
Running sql2005
View 1 Replies
View Related
Jul 8, 2013
I have 2 requests for desperate Hélio..
1) is there any way to run a query over a query without having to create a table with the results of the first query? (would drop table work? If so, how?
2) how can i define input variables the same way i do in excel? I am trying to run a couple of simulations based on 2 core inputs (in excel i would just do a data table)
View 7 Replies
View Related
Oct 15, 2007
Hi,I'm new to SQL Server, but an experienced .Net developer. I'm tryingto accomplish a query the most efficient way possible. My question isif you can define a temporary variable within a query to store tablesor fields. (Like the LET clause of LINQ) My query makes use ofsubqueries which filter my table (WHEREs, not SELECTs) in the sameexact way. I'd like to have a subquery at the beginning of my queryto filter the table(s) once, and then SELECT off it of later in thequery.Here is an (utterly poor) example. No, this is not from my project.My filter is a little more complex than 'c=@p'.('c' is a column/field, 't' is a table', '@p' is a parameter)SELECT *FROM (SELECT COUNT(c) FROM t WHERE c=@p GROUP BY c)CROSS JOIN (SELECT c FROM t WHERE c=@p)Bottom line, would something like the following be possible?@v = (SELECT c FROM t WHERE a=@p)SELECT *FROM (SELECT COUNT(c) FROM @v GROUP BY c)CROSS JOIN (SELECT c FROM @v)I'd like to know if this is possible within a query, but I can move toa Stored Procedure if I must. (I'll still need help then.)Thank you all
View 3 Replies
View Related
Oct 3, 2007
Hi I'm a n00b at ASP.Net and C# but the company I work for requires me to know this and develop their website using these languages.
Anyway I've been doing pretty good so far I got the page looking as it should etc and databases all set up, now I've hit my first real problem... I am using Visual Studio 2005 and in the Web Developer section. I want to make a SELECT query using the <asp:LoginName> control as the where clause.
e.g. if admin logs in there is a welcome message : Welcome Admin now I want to use the 'Admin' <asp:LoginName> as the SELECT in my query i.e. SELECT * FROM tbla WHERE ([fldCustomerCode] = 'LoginName' )
I was just really wondering if that is in the .aspx file or the aspx.cs code behind file?
Thanks for any help given
View 4 Replies
View Related
Dec 24, 2003
I’ve reconfigured Microsoft’s IBS Store shopping cart to function within a small e-commerce website. What I am trying to do is to modify the code slightly in order to use a third party credit card processing center. The situation is this: once the customer clicks the final "check out" button, a stored procedure writes all of the product ordering information into the database. I, then, capture what they're wanting to purchase with the following SQL statement:
Dim strSQL as String = "Select orderID, modelNumber from orderDetails" & _
"where CustomerID = " & User.Identity.Name & _
"And orderid = (SELECT MAX(orderid)FROM orderDetails" & _
"where CustomerID = " & User.Identity.Name & ")"
What I would like to do is assign specific values to variables based off of the above query. For example:
Dim orderItem as String = (all of the modelNumbers from the query)
Dim orderIdItem as String = (all of the orderIDs from the query)
How do I do this?? Any help is much appreciated! Thanks in advance.
Ron
View 6 Replies
View Related
Dec 15, 2004
Hey guys,
I was wondering if there was a way to set a local variable from the results of a query or stored procedure.
For example, I have a stored procedure or a select statement that returns 1 row, with columns "a" "b" "c" "d"
I want to set my variable to be the value in column "b"
Is there a way to do that? I'm new to tsql, so any code would help.
I tried this, but I know my syntax is messed up
declare @myvar as integer
set @myvar = (execute mystoredProcedure).b
thanks
View 4 Replies
View Related
Mar 28, 2001
I'm trying to create a stored procedure with a dynamic update statement depending on the variables received. I receive a sql error "Incorrect syntax near the keyword 'WHERE'." although the variable, @tempvar, appears correct. Any ideas?
----
DECLARE @tempvar varchar(1025), @SolutionDetail varchar(1000), @hours varchar(12), @id int
if @SolutionDetail <> " "
set @tempvar = "SolutionDetail = " + "'" +@SolutionDetail + "'"
IF @hours <> " "
set @tempVar = @tempvar + ", hours = " + "'" + @hours +"'"
UPDATE WorkOrderTbl SET @tempvar
WHERE workorderid = @id
View 3 Replies
View Related
Jul 23, 2005
I am having trouble inserting two queries...I am trying to insert annew item(pk) into a table in one query, and then inserting an item(fk)in another table that relates to the other item just created in thefirst. The problem is that in order for the second query to work, thefirst has to exist in the first table before it will work. Is there away of running the first query first and then the next. Here is what Ihave:<cfquery name="q_insert" datasource="#dsn#">INSERT INTO eccn(eccn_num,eccn_brief_descrip,eccn_full_descrip,eccn_reason_controlled)VALUES('1D001','TEST','TEST INPUT AND SEARCH','TESTING THE INPUT AND SEARCH PERFORMANCE')</cfquery><cfquery name="q_insert2" datasource="#dsn#">INSERT INTO eccN_interrelationship(eccn_num,related_eccn_num)VALUES('1D001','1B001')</cfquery>
View 1 Replies
View Related
Jan 18, 2007
Hi, I'm a compleate noob and trying to learn c# and wmi. I have used WMI queries in vbscripts but I want to take things a bit further now and read a server name from a SQL db and query WMI (eg. disk space available) then record it back into SQL. I'm really struggling on how to do this.
I written the code to query WMI (SELECT * FROM Win32_LogicalDisk) but referencing it to DB's is something I can't do!
Can anyone help with this?
View 1 Replies
View Related
Mar 19, 2006
Is it possible to use variable name to dynamically define a query in a stored procedure? EX:
@Column = 'COUNT(*)'
@Category = 'Products'
@Table = 'Items. + @Category
SELECT @Column
FROM @Table
View 1 Replies
View Related
Oct 28, 2004
Hi all,
If I have a query string that is to be stored in a database, for example
Code:
SELECT prod_id, prod_name, prod_desc FROM products WHERE prod_id = 'variable'
how can I put a variable identifier into this string so that when I need to run the query I call it from the database and simply insert the relevant variable in the correct place.
Is there an appropriate way of doing this in MS SQL Server?
Thanks
Tryst
View 1 Replies
View Related
Oct 10, 2006
When I want to user variable in the name of the database, I have an error. What's wrong with my code ?
DECLARE @BASE_SOURCE varchar (30),@BASE_DESTI varchar(30),@TEST varchar(30)
set @BASE_SOURCE='BASE1'
set @BASE_DESTI='BASE2'
select * from @BASE_SOURCE.dbo.FOURNISS
Msg*170, Niveau*15, État*1, Ligne*4
Ligne 4 : syntaxe incorrecte vers '.'.
View 2 Replies
View Related
Mar 16, 2007
Hi, I have a SQLDataSource binding to a GridView and can come to the page either with or without a query string attached:
/ProjectManagement/reporting/project.aspx
/ProjectManagement/reporting/project.aspx?portfolio=3
When it comes with a query string, I can see in SQL Server profiler it executes and I get all the right data. When it is an empty string, or with no "?portfolio=" on it, it won't even execute against SQL server. Any ideas?
<asp:GridView ID="grid" runat="server" Width="600px"
ShowHeader="false"
AutoGenerateColumns="false"
DataSourceID="DSportfolio"
AllowSorting = "true"
AllowPaging = "true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
.............
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="DSportfolio" ConnectionString="<%$ AppSettings:SQLConnection1 %>"
SelectCommand="uspSELECT_PROJECT"
SelectCommandType="StoredProcedure"
runat="server">
<SelectParameters>
<asp:QueryStringParameter Name="p_PORTFOLIOID" QueryStringField="portfolio" />
</SelectParameters>
</asp:SqlDataSource>
Thanks,
James
View 2 Replies
View Related
Mar 30, 2007
I have set up roles in my asp.net application, have created my various folders and pages and have the login stuff working nicely, inlcuding displaying the logged-in user's name on screen. What I want to do is read that value (displayed via the LoginName control) as a Parameter in a SqlDataSource query which extracts user-specific data from a sql server 2k datasource. Essentially, if the logged-in user's UserName is jbloggs - I would like to be able to read that into my sql query as @UserName or the like.
If possible, I am trying to do this via the Visual Studio interface, not as code-behind.
Many thanks,
Doc Brown.
View 2 Replies
View Related
Nov 7, 2007
I am trying to reload an AJAX control without reloading the page. This question may belong under AJAX, but I'm not sure if I'm managing the SqlDataSource correctly. I want to set the SelectCommand to a new SQL statement and refresh the form on the screen. My code is below. It doesn't seem to be working. Do I need to call something else or is this correct and the problem is with that nasty AJAX?SqlDataSource oSqlDataSource1 = (SqlDataSource) oContentPlaceHolder1.FindControl("SqlDataSource1");oSqlDataSource1.SelectCommand = "SELECT * FROM WorkHistory WHERE WorkHistoryID = " + sWorkHistoryID;oSqlDataSource1.Select(DataSourceSelectArguments.Empty);
View 2 Replies
View Related
Jan 30, 2006
I'm using a sql data source and I need to perform a foreach query. I have a collection of id's and I need to hit my database (the one available via sql data source) for each of the id's in the collection. I know that the sql data source returns a data view and it can be coverted to a data table. What's the best way to query a database using the sql data source ojbect for each id in a collection? Here's my code.
<code>
private void GetJobsFromPSI(JobQueueCollection jobs)
{
// Create a data view.
DataView dv = new DataView();
// Get the id's.
JobQueueCollection jobs = GetJobsFromQueue(Membership.GetUser().ProviderUserKey());
// Now that we have all of the user id's we
// need to call out the jobs from PSI.
foreach (JobQueue job in jobs)
{
// Get query for each id in the job collection.
// Somehow add a new datarowview to the data view for each
// query.
}
}
</code>
View 1 Replies
View Related
May 12, 2006
Hi folks, I'm having some trouble here.
In a database, there's a table that contains information about items or units in a flow; tbl_item. One of the columns is named SubLocationID (int) and it says where in the flow the unit is located.
Another table is called tbl_sublocation, and it contains information on each sublocation, where of course SubLocationID is the primary key. In this table, there's a column named SubLocationName which gives the user a name to relate to instead of just a number.
Code:
SELECT
SubLocationID,
count(SubLocationID) AS Units
FROM
tbl_item
GROUP BY
SubLocationID
HAVING (COUNT(SubLocationID) > 1)
Now, I use this query to get information if there's any sublocations that have two or more items on them. It works just fine, but I want to display SubLocationName from tbl_sublocation instead of SubLocationID, and I just can't figure out how.
Anyone got any sugestions? Thanks in advance.
View 4 Replies
View Related
Jul 13, 2004
Hi,
I think I'm just braindead or simply thick...since this shouldn't be that hard, but I'm stumped right now.
So, I'm trying to retrieve from a table, with a sql stored procedure with the sql like
"select height, width, depth from products where id=@idinput"
OK, so this part is easy, but if I wanted to say, return this to my code and assign height to a variable Ht, width to Wd and depth to Dp, how could I do that?
This is what I've got so far...
[code]
cmdSelect = New SqlCommand( "GetProd", connstr )
cmdSelect.CommandType = CommandType.StoredProcedure
dbcon.Open()
dbcon.Close()
[/code]
The main prob is just what to connect this record to in order to access the individual fields.
Thx :)
View 2 Replies
View Related
May 18, 1999
Hi!
Here is a snap form my code
declare @max_id int
declare @the_db varchar (30)
select @the_db = 'mydb'
exec ("select """ @max_id """ = max(id) from " + @the_db + "..mytable")
I got syntex error for the @max_id. The script is writen based on the sample given in MSSQL6.5 Book Online, chapter "Transaction-SQL Reference 6.0" section "C"->"Control-Flow Lang."->"Control-Flow Examples"
Can someone help me on how to assign a value to a local variable from a dynamic query.
Thank for any help in advance
Hank Lee
View 1 Replies
View Related