Refer To Webform Fields In Insert Statement

Aug 3, 2007

Can someone help with this? Let me know if what I'm trying to do is possible...

Here's code example:


@ClientID int,

@QuoteID int,

@Base real,

@One real,

@DwellingLimit real

AS

BEGIN

Insert Into tblOne(ClientID,QuoteID,GuideID,GuideRate,GuideMult,Premium)

Select @ClientID, @QuoteID, GuideID,GuideRate, @+"GuideMult"+,GuideRate*GuideMult

From tblTwo

Where Choose = 'True';

END


I need the value stored in tblTwo.GuideMult (ie. One, BaseRate) to be translated
into the numerical value shown on a webform (ie. @One, @BaseRate) and then
insert the numerical values into tblOne.GuideMult

Clear as mud? Does somebody have a better way to do this?

View 1 Replies


ADVERTISEMENT

Strange Problem: SQL Insert Statement Does Not Insert All The Fields Into Table From Asp.net C# Webpage

Apr 21, 2008

An insert statement was not inserting all the data into a table. Found it very strange as the other fields in the row were inserted. I ran SQL profiler and found that sql statement had all the fields in the insert statement but some of the fields were not inserted. Below is the sql statement which is created dyanmically by a asp.net C# class. The columns which are not inserted are 'totaltax' and 'totalamount' ...while the 'shipto_name' etc...were inserted.there were not errors thrown. The sql from the code cannot be shown here as it is dynamically built referencing C# class files.It works fine on another test database which uses the same dlls. The only difference i found was the difference in date formats..@totalamount=1625.62,@totaltax=125.62are not inserted into the database.Below is the statement copied from SQL profiler.exec sp_executesql N'INSERT INTO salesorder(billto_city, billto_country, billto_line1, billto_line2, billto_name,billto_postalcode, billto_stateorprovince, billto_telephone, contactid, CreatedOn, customerid, customeridtype,DeletionStateCode, discountamount, discountpercentage, ModifiedOn, name, ordernumber,pricelevelid, salesorderId, shipto_city, shipto_country,shipto_line1, shipto_line2, shipto_name, shipto_postalcode, shipto_stateorprovince,shipto_telephone, StateCode, submitdate, totalamount,totallineitemamount, totaltax ) VALUES(@billto_city, @billto_country, @billto_line1, @billto_line2,@billto_name, @billto_postalcode, @billto_stateorprovince, @billto_telephone, @contactid, @CreatedOn, @customerid,@customeridtype, @DeletionStateCode, @discountamount,@discountpercentage, @ModifiedOn, @name, @ordernumber, @pricelevelid, @salesorderId,@shipto_city, @shipto_country, @shipto_line1, @shipto_line2,@shipto_name, @shipto_postalcode, @shipto_stateorprovince, @shipto_telephone,@StateCode, @submitdate, @totalamount, @totallineitemamount, @totaltax)',N'@billto_city nvarchar(8),@billto_country nvarchar(13),@billto_line1 nvarchar(3),@billto_line2 nvarchar(4),@billto_name nvarchar(15),@billto_postalcode nvarchar(5),@billto_stateorprovince nvarchar(8),@billto_telephone nvarchar(3),@contactid uniqueidentifier,@CreatedOn datetime,@customerid uniqueidentifier,@customeridtype int,@DeletionStateCode int,@discountamount decimal(1,0),@discountpercentage decimal(1,0),@ModifiedOn datetime,@name nvarchar(33),@ordernumber nvarchar(18),@pricelevelid uniqueidentifier,@salesorderId uniqueidentifier,@shipto_city nvarchar(8),@shipto_country nvarchar(13),@shipto_line1 nvarchar(3),@shipto_line2 nvarchar(4),@shipto_name nvarchar(15),@shipto_postalcode nvarchar(5),@shipto_stateorprovince nvarchar(8),@shipto_telephone nvarchar(3),@StateCode int,@submitdate datetime,@totalamount decimal(6,2),@totallineitemamount decimal(6,2),@totaltax decimal(5,2)',@billto_city=N'New York',@billto_country=N'United States',@billto_line1=N'454',@billto_line2=N'Road',@billto_name=N'Hillary Clinton',@billto_postalcode=N'10001',@billto_stateorprovince=N'New York',@billto_telephone=N'124',@contactid='8DAFE298-3A25-42EE-B208-0B79DE653B61',@CreatedOn=''2008-04-18 13:37:12:013'',@customerid='8DAFE298-3A25-42EE-B208-0B79DE653B61',@customeridtype=2,@DeletionStateCode=0,@discountamount=0,@discountpercentage=0,@ModifiedOn=''2008-04-18 13:37:12:013'',@name=N'E-Commerce Order (Before billing)',@ordernumber=N'BRKV-CC-OKRW5764YS',@pricelevelid='B74DB28B-AA8F-DC11-B289-000423B63B71',@salesorderId='9CD0E11A-5A6D-4584-BC3E-4292EBA6ED24',@shipto_city=N'New York',@shipto_country=N'United States',@shipto_line1=N'454',@shipto_line2=N'Road',@shipto_name=N'Hillary Clinton',@shipto_postalcode=N'10001',@shipto_stateorprovince=N'New York',@shipto_telephone=N'124',@StateCode=0,@submitdate=''2008-04-18 14:37:10:140'',@totalamount=1625.62,@totallineitemamount=1500.00,@totaltax=125.62
 
thanks

View 7 Replies View Related

Error Message: Report Item Expressions Can Only Refer To Fields Within The Current Data Set Scope Or, If Inside An Aggregate, T

May 14, 2007

Hi



I have a old report that was pointing to a different database, and i changed the connection string for that report and changed the field names (As per my new stored Procedure). In some places I keep getting this run time error, i have tried looking for all the hidden references to this field and i cannot find any parameter that the old database had. The error messages that i get are as follows:



[rsFieldReference] The Hidden expression for the table €˜tblContactInfo€™ refers to the field €˜PL_Admin_ShowInKit€™. Report item expressions can only refer to fields within the current data set scope or, if inside an aggregate, the specified data set scope.

[rsFieldReference] The Hidden expression for the table €˜tblContactInfo€™ refers to the field €˜PL_FA_ShowInKit€™. Report item expressions can only refer to fields within the current data set scope or, if inside an aggregate, the specified data set scope.

[rsFieldReference] The Hidden expression for the table €˜tblWithdrawals€™ refers to the field €˜PW_Comment€™. Report item expressions can only refer to fields within the current data set scope or, if inside an aggregate, the specified data set scope.





Can Someone please help me out as to how should i get rid of these error messages, they are kinda driving me nuts.



Regards,

Karen



View 3 Replies View Related

Best Way To Insert Large Amounts Of Data From A Webform To SQL Server 2005

Oct 21, 2007

HiI have a VB.net web page which generates a datatable of values (3 columns and on average about 1000-3000 rows).What is the best way to get this data table into an SQL Server? I can create a table on SQL Server no problem but I've found simply looping through the datatable and doing 1000-3000 insert statements is slow (a few seconds). I'd like to make this as streamlined as possible so was wondering is there is a native way to insert all records in a batch via ADO.net or something.Any ideas?ThanksEd

View 1 Replies View Related

Help ! How Do I Refer To The Deleted Table Into A Trigger Statement ?

Jul 20, 2005

Hi there,Could somebody post some simple example how one can refer toa column in the 'deleted' temporary table within a trigger definition ?Should the 'deleted' and 'inserted' temp tables be declared, or they are'implied' ?I keep having this msg when trying to create a trigger"The column prefix 'deleted' does not match with a table name or alias nameused in the query"Thanks for your inputs,Eddy.

View 2 Replies View Related

Need Help With Insert Statement On Table With Several Non-null Fields

Apr 30, 2007

On my aspx page I have a basic sqldatasource and gridview - both were set up using the wizards. The SQL Server 2000 database table that the sqldatasource is querying has some fields in it that are set to not allow nulls, however, the gridview control is not displaying all of the fields in the table - including some of the non-null fields.
My problem is, when I run an insert on the table from my aspx page, I get an error that says: "Cannot insert the value NULL into column 'ColumnName', table 'TableName'; column does not allow nulls. INSERT fails. The statement has been terminated."
The 'ColumnName', as you may have guessed, is one of the aforementioned columns that doesn't allow nulls, but isn't in the GridView.
How can I do an insert on this table without messing with the non-null fields. Those fields are relevant to the purposes of the gridview, so I don't want to display them, let alone allow editing of them.
Any suggestions on my options would be greatly appreciated!
Thanks
Capella07

View 2 Replies View Related

Want To Compare Webform Input To Database

Apr 9, 2008

 Hello, I am writing a website (in vb) to allow for room use reservations and I am looking for a way to compare the selected start and end times which are date-time format to records already in the database for that  day/time  and specific room.  If the selected time does not fall within an already reserved time frame I then want to insert it into the table.  I have already written a procedure to do the inserting and that works fine.  I just want to validate it before calling the insert.  Any ideas?  The fields to be validated on the form are textboxes containing date time which populate as read only after the time selection is chosen from dropdown. Thanks in advance It's greatly appreciated.

View 7 Replies View Related

What Am I Doing Wrong? I Just Want To Modify My Database From A Webform.

Feb 20, 2006

Windows XP
SQL Expresss 2005
SQL Express 2005 Manager
 
I simply want to edit and data I have in a database that I made with Express Manager. This worked before .Net 2.0. Now, I have the table displayed as a datagrid with an "edit" pushbutton associated with each row in the database table. When I click on the "edit" pushbutton to edit a specific row in the database table, instead of posting me to a page where the chosen row is editable, I am posted back to the same page without the chosen row availible to be edited.
What am I doing wrong? How can I fix this? I am totally new to this so any help would be appreciated.
Cheers!
<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="iso-8859-1" EnableEventValidation="false" %><%@ Register TagPrefix="MM" Namespace="DreamweaverCtrls" Assembly="DreamweaverCtrls,version=1.0.0.0,publicKeyToken=836f606ede05d46a,culture=neutral" %><MM:DataSet id="dsParts"runat="Server"IsStoredProcedure="false"ConnectionString='<%# System.Configuration.ConfigurationSettings.AppSettings["MM_CONNECTION_STRING_PartsAreUs"] %>'DatabaseType='<%# System.Configuration.ConfigurationSettings.AppSettings["MM_CONNECTION_DATABASETYPE_PartsAreUs"] %>'CommandText='<%# "SELECT * FROM dbo.Parts" %>'Debug="true">  <EditOps>    <EditOpsTable Name="dbo.Parts" />      <Parameter Name="Name" Type="VarChar" />      <Parameter Name="Description" Type="NVarChar" />      <Parameter Name="Price" Type="Money" />      <Parameter Name="PartID" Type="Int" IsPrimary="true" />    </EditOps></MM:DataSet><MM:PageBind runat="server" PostBackBind="true" /><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><title>Untitled Document</title></head><body><form runat="server">  <asp:DataGrid id="dgParts"   runat="server"   AllowSorting="False"   AutoGenerateColumns="false"   CellPadding="3"   CellSpacing="0"   ShowFooter="false"   ShowHeader="true"   DataSource="<%# dsParts.DefaultView %>"   PagerStyle-Mode="NextPrev"         DataKeyField="PartID"  onCancelCommand="dsParts.OnDataGridCancel"   onEditCommand="dsParts.OnDataGridEdit"   onUpdateCommand="dsParts.OnDataGridUpdate"   onItemDataBound="dsParts.OnDataGridItemDataBound" >    <HeaderStyle HorizontalAlign="center" BackColor="#E8EBFD" ForeColor="#3D3DB6" Font-Name="Verdana, Arial, Helvetica, sans-serif" Font-Bold="true" Font-Size="smaller" />    <ItemStyle BackColor="#F2F2F2" Font-Name="Verdana, Arial, Helvetica, sans-serif" Font-Size="smaller" />    <AlternatingItemStyle BackColor="#E5E5E5" Font-Name="Verdana, Arial, Helvetica, sans-serif" Font-Size="smaller" />    <FooterStyle HorizontalAlign="center" BackColor="#E8EBFD" ForeColor="#3D3DB6" Font-Name="Verdana, Arial, Helvetica, sans-serif" Font-Bold="true" Font-Size="smaller" />    <PagerStyle BackColor="white" Font-Name="Verdana, Arial, Helvetica, sans-serif" Font-Size="smaller" />    <Columns>    <asp:EditCommandColumn         ButtonType="PushButton"         CancelText="Cancel"         EditText="Edit"         HeaderText="Edit"         UpdateText="Update"         Visible="True"/>    <asp:BoundColumn DataField="PartID"         HeaderText="PartID"         ReadOnly="true"         Visible="True"/>    <asp:BoundColumn DataField="Name"         HeaderText="Name"         ReadOnly="false"         Visible="True"/>    <asp:BoundColumn DataField="Description"         HeaderText="Description"         ReadOnly="false"         Visible="True"/>    <asp:BoundColumn DataField="Price"         HeaderText="Price"         ReadOnly="false"         Visible="True"/>    </Columns>  </asp:DataGrid></form></body></html>
 

View 3 Replies View Related

Webform Time Out Trying To Retrieve From Different Tables

Jun 9, 2006

I'm having a problem retrieving information from two different tables. Everytime i run a query which i type a source id into a textbox my page keeps timing out. What could be the problem? The tables i'm pulling from is profiles and phone. Here is the code. If someone could tell me what's going on id apperciate it. Thanks!
 
Dim queryString As String = "SELECT [profiles].[date_added], [profiles].[source_id], [RP_profiles].[fnam"& _"e], [profiles].[lname], [profiles].[title], [phone].[number], [RP_phone"& _"].[source_id] FROM [profiles], [phone] WHERE ([profiles].[source_id] = "& _"@source_id)"
 
 

View 3 Replies View Related

How Can I Retrieve The Data Back Into The Webform From The Database?

Feb 27, 2008

Hi,I m using vwd2005 and sql express,c#.I have a question here.In my database i have a table named Table1(id,name,age,country,email,phone) The values for these fields are inserted from the webform.Id is auto generated.name and age is passed from the textbox within the webform.country is passed from dropdownlist within the webform.email and phone is passed from listbox(multiple email and phone) within the webform.Now my problem is i want to retrieve all these row values back into the textboxes,dropdownlist and listbox at the same timeon the click of the retrieve button within the web form . Further more i want to make few changes on it and update the database on the click of another button update within the form.I hope u are getting it.How would the query would be in this case.?can u demonstrate the concept in one simple running example along with code?thanks.jack. 

View 3 Replies View Related

**I M Not Able To RETRIEVE Data Back Into Webform From The Database?

Mar 25, 2008

Hello Everyone,I 've trying to retreive data back into webform from the database from past couple of weeks.But i m not able to retrieve it completely.Here is my scenario.I've tried to explain in detail but in simple language.I hope u will get my point.Ok here it is.plz run my code:-i have three tables in sql.they are:-grup(id,grp)      (1,abc)      (2,xyz)      organization(id,oid,gid,organisation,orgphone)                  (1,1,1,ibm,1234567)                  (2,1,2,microsoft,6543210)                  (3,2,1,oracle,7654323)                  (4,2,2,apple,9876543)  userform(id,title,name,address,email,organizationid)              (1,mr,jack,usa,jack@jack.com,1) userform.aspx page<%@ Page Language="C#" AutoEventWireup="true" CodeFile="userform.aspx.cs" Inherits="userform" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>Untitled Page</title></head><body>    <form id="form1" runat="server">    <div>        <div style="text-align: center">            <table>                <tr>                    <td style="width: 100px">                        Title</td>                    <td style="width: 100px">                        <asp:DropDownList ID="DropDownList1" runat="server">                            <asp:ListItem>mr</asp:ListItem>                            <asp:ListItem>miss</asp:ListItem>                            <asp:ListItem>ms</asp:ListItem>                        </asp:DropDownList></td>                </tr>                <tr>                    <td style="width: 100px">                        Name</td>                    <td style="width: 100px">                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>                </tr>                <tr>                    <td style="width: 100px">                        Add</td>                    <td style="width: 100px">                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>                </tr>                <tr>                    <td style="width: 100px; height: 26px;">                        Email</td>                    <td style="width: 100px; height: 26px;">                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td>                </tr>            </table>        </div>        </div>        <div style="text-align: center">            <div>                <div>                    <asp:ScriptManager ID="ScripManager1" runat="server">                    </asp:ScriptManager>                    <div>                        <table>                            <tr>                                <td style="width: 100px">                        Group</td>                                <td style="width: 100px">                                   
<asp:DropDownList ID="ddl1" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddl1_SelectedIndexChanged">                                    </asp:DropDownList></td>                            </tr>                        </table>                        &nbsp;</div>                    <div>                        <asp:UpdatePanel ID="UpdatePanel1" runat="server">                            <ContentTemplate>                                <table>                                    <tr>                                        <td>                        Organisation&nbsp;</td>                                        <td>                                           
<asp:DropDownList ID="ddl2" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddl2_SelectedIndexChanged">                                            </asp:DropDownList>&nbsp;                                        </td>                                    </tr>                                    <tr>                                        <td>                        org-phone&nbsp;</td>                                        <td>                        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>&nbsp;</td>                                    </tr>                                    <tr>                                        <td>                                        </td>                                        <td>                                           
<asp:TextBox ID="TextBox5" runat="server"
Width="45px"></asp:TextBox></td>                                    </tr>                                </table>                            </ContentTemplate>                            <Triggers>                                <asp:AsyncPostBackTrigger ControlID="ddl1" EventName="SelectedIndexChanged" />                            </Triggers>                        </asp:UpdatePanel>                        <br />                        <table>                            <tr>                                <td style="width: 100px">                        <asp:Button ID="Button1" runat="server" Text="save" OnClick="Button1_Click" />                                </td>                                <td style="width: 100px">                                    <asp:Button ID="Button3" runat="server" Text="update" /></td>                                <td style="width: 100px">                        <asp:Button ID="Button2" runat="server" Text="cancel" /></td>                            </tr>                        </table>                    </div>                </div>            </div>        </div>    </form></body></html>userform.cs page public partial class userform : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        if (!Page.IsPostBack)        {            AssignDDLDataSource();            ddl1_SelectedIndexChanged(null, null);        }    }        private void AssignDDLDataSource()    {                // SqlConnection             string sqlQry = "SELECT GRP DISPMEM, ID VALMEM FROM GRUP";        SqlCommand cmd = new SqlCommand(sqlQry, con);        ddl1.DataSource = cmd.ExecuteReader();        ddl1.DataTextField = "DISPMEM";        ddl1.DataValueField = "VALMEM";        ddl1.DataBind();    }    protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)    {        AssignSubjectDDL(ddl1.SelectedValue);    }    private void AssignSubjectDDL(string val)    {       // SqlConnection        string sqlQry = "SELECT ORGANISATION DISPMEM, GID VALMEM FROM ORGANIZATION where OID = '" + val + "'";        SqlCommand cmd1 = new SqlCommand(sqlQry, con);        ddl2.DataSource = cmd1.ExecuteReader();        ddl2.DataTextField = "DISPMEM";        ddl2.DataValueField = "VALMEM";        ddl2.DataBind();        ddl2_SelectedIndexChanged(null, null);    }    protected void ddl2_SelectedIndexChanged(object sender, EventArgs e)    {        AssignTextBoxValues(ddl1.SelectedValue, ddl2.SelectedValue);    }    private void AssignTextBoxValues(string teamval, string memval)    {         // SqlConnection       
string sqlQry = "Select ID,ORGANISATION,ORGPHONE from ORGANIZATION
where OID = '" + teamval + "' AND GID = '" + memval + "'";        SqlCommand cmd = new SqlCommand(sqlQry, con);        SqlDataReader rdr = cmd.ExecuteReader();        while (rdr.Read())        {            TextBox5.Text = rdr["ID"].ToString().Trim();            TextBox4.Text = rdr["ORGPHONE"].ToString().Trim();        }    }    protected void Button1_Click(object sender, EventArgs e)    {       // SqlConnection       
string sqlQry = "INSERT into USERFORM (title, name, address, email,
organizationid) VALUES(@title,@name,@address,@email,@organizationid)";        SqlCommand cmd = new SqlCommand(sqlQry, con);        cmd.CommandType = CommandType.Text;        cmd.Parameters.AddWithValue("title", DropDownList1.SelectedValue.Trim());        cmd.Parameters.AddWithValue("name", TextBox1.Text);        cmd.Parameters.AddWithValue("address", TextBox2.Text);        cmd.Parameters.AddWithValue("email", TextBox3.Text);        cmd.Parameters.AddWithValue("organizationid", TextBox5.Text);        cmd.ExecuteNonQuery();        Response.Redirect("detailsview.aspx");    }} detailsview.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="detailsview.aspx.cs" Inherits="detailsview" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>Untitled Page</title></head><body>    <form id="form1" runat="server">    <div>        <asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True" EnablePagingCallbacks="True"            Height="50px" HorizontalAlign="Center" Width="125px">        </asp:DetailsView>        </div>    </form></body></html> detailsview.cspublic partial class detailsview : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        //SqlConnection        
string str = "select title,name,address,email,grp,organisation,orgphone
from userform as a inner join organization as b on
a.organizationid=b.id inner join grup as c on b.oid=c.id";        SqlDataAdapter oda = new SqlDataAdapter(str, conn);        conn.Open();        DataSet ods = new DataSet();        oda.Fill(ods, "info");        DetailsView1.DataSource = ods.Tables["info"].DefaultView;        DetailsView1.DataBind();              }}My problem :-Now when user fills up the userform and clicks the save button the details are shown in the details view.Now i want to add a Edit hyperlink next to the records in the detailsview so that when i click on it i would be redirected to userform.aspx form with all the textboxes,dropdownlist etc be populated from the related data from the database.(here table userform).Now i want to edit these data in the userform.aspx page and finally when i click the update button at end i want all the data be updated in the database aswell as in details view too.at the same time i want this form to redirect to detailsview.aspx .i hope ur getting it?i m able to do partial part only.Not completely. So can u now  help me modify the code accordingly?Thanks in advance.Jack.  

View 4 Replies View Related

DB Engine :: Can't Use The MERGE Statement / How To Design WHERE Condition For Insert Statement

Nov 5, 2015

I've have a need with SQL Server 2005 (so I've no MERGE statement), I have to merge 2 tables, the target table has 10 fields, the first 4 are the clustered index and primary key, the source table has the same fields and index.Since I can't use the MERGE statement (I'm in SQL 2005) I have to make a double step operation, and INSERT and an UPDATE, I can't figure how to design the WHERE condition for the insert statement.

View 2 Replies View Related

Statement To Identify Certain Fields

Sep 19, 2013

I am extract data from one of our Sql servers with the code below

Code:
Select SectDesc, PrGDesc, 'Product Description'=SetDescF, ProdSet, ProdSect, SectChar, Prdct.ProdGrp, OrigPr

From Prdct

INNER JOIN qryPRDGroupDets on Prdct.ProdGrp=qryPRDGroupDets.PGCode

where supersed =''
And OrigPr Not Like '9%' And OrigPr Not Like '%MDM%'
And LISTPR1>'0' And STANCOST>'0'

Which works fine, but what I need to do is reference the "OrigPr" field and mark it as "valid" or "Invalid", the "OrigPr" the field contains alpha numeric data e.g. A000, A001, A002 - ZZ99 and so on, amongst all of the potential different types of codes we have codes that end in treble Zero (0) e.g. A000 which are valid, but if they end in double 00 e.g. AA00 then this is invalid, the problem I have is I can't just add

Code:
'Marker'= Case When Right(OrigPr, 2) = '00' Then 'Invalid' ELSE 'Valid' End

For it will mark the A000 as invalid, is there a way of getting around this...

View 6 Replies View Related

Help With SQL If Statement And Adding Fields Together

Jul 23, 2005

I have a query that I need a hand on. I am trying to add togther somefiends based on values of another.What I would like to add a billing total by saying more or less thefollowing:SELECT labor_hours, labor_cost, expidite_fee, flat_rate,include_repair_cost, include_cal, include_flat_rate, include_parts,cur_bill,(labor_hours * labor_cost) AS labor_total,(ISNULL((SELECT TOP 1 cal_cost FROM calID WHERE orderID=79559 ORDER BYdateCAL DESC),0)) AS cal_total,(ISNULL((SELECT SUM((qty * cost) + premium_charge) AS gptotal FROMrepair_partsID WHERE orderID=79559),0) +ISNULL((SELECT SUM(qty_needed * cust_cost) AS gnptotal FROMmisc_part_assocID WHERE orderID=79559),0)) AS parts_total,((labor_hours * labor_cost) + expidite_fee + flat_rate +ISNULL((SELECT TOP 1 cal_cost FROM calID WHERE orderID=79559 ORDER BYdateCAL DESC),0) +ISNULL((SELECT SUM((qty * cost) + premium_charge) AS gptotal FROMrepair_partsID WHERE orderID=79559),0) +ISNULL((SELECT SUM(qty_needed * cust_cost) AS gnptotal FROMmisc_part_assocID WHERE orderID=79559),0)) AS actual_total,(expidite_feeIF include_repair_cost = 1+ (labor_hours * labor_cost)IF include_flat_rate = 1+ flat_rateIF include_cal = 1+ ISNULL((SELECT TOP 1 cal_cost FROM calID WHERE orderID=79559 ORDERBY dateCAL DESC),0)IF include_parts = 1+ ISNULL((SELECT SUM((qty * cost) + premium_charge) AS gptotal FROMrepair_partsID WHERE orderID=79559),0) +ISNULL((SELECT SUM(qty_needed * cust_cost) AS gnptotal FROMmisc_part_assocID WHERE orderID=79559),0)) AS billing_totalFROM view_inventoryWHERE orderID=79559I know the IF part is whacked, that's where I need the help. Is thistype of thing even possible? Or even efficent? Is it wise to subqueryfor totals (not like I have a choice based on the applicationrequirements)? help.

View 2 Replies View Related

Cannot INSERT Data To 3 Tables Linked With Relationship (INSERT Statement Conflicted With The FOREIGN KEY Constraint Error)

Apr 9, 2007

Hello
 I have a problem with setting relations properly when inserting data using adonet. Already have searched for a solutions, still not finding a mistake...
Here's the sql management studio diagram :

 and here goes the  code1 DataSet ds = new DataSet();
2
3 SqlDataAdapter myCommand1 = new SqlDataAdapter("select * from SurveyTemplate", myConnection);
4 SqlCommandBuilder cb = new SqlCommandBuilder(myCommand1);
5 myCommand1.FillSchema(ds, SchemaType.Source);
6 DataTable pTable = ds.Tables["Table"];
7 pTable.TableName = "SurveyTemplate";
8 myCommand1.InsertCommand = cb.GetInsertCommand();
9 myCommand1.InsertCommand.Connection = myConnection;
10
11 SqlDataAdapter myCommand2 = new SqlDataAdapter("select * from Question", myConnection);
12 cb = new SqlCommandBuilder(myCommand2);
13 myCommand2.FillSchema(ds, SchemaType.Source);
14 pTable = ds.Tables["Table"];
15 pTable.TableName = "Question";
16 myCommand2.InsertCommand = cb.GetInsertCommand();
17 myCommand2.InsertCommand.Connection = myConnection;
18
19 SqlDataAdapter myCommand3 = new SqlDataAdapter("select * from Possible_Answer", myConnection);
20 cb = new SqlCommandBuilder(myCommand3);
21 myCommand3.FillSchema(ds, SchemaType.Source);
22 pTable = ds.Tables["Table"];
23 pTable.TableName = "Possible_Answer";
24 myCommand3.InsertCommand = cb.GetInsertCommand();
25 myCommand3.InsertCommand.Connection = myConnection;
26
27 ds.Relations.Add(new DataRelation("FK_Question_SurveyTemplate", ds.Tables["SurveyTemplate"].Columns["id"], ds.Tables["Question"].Columns["surveyTemplateID"]));
28 ds.Relations.Add(new DataRelation("FK_Possible_Answer_Question", ds.Tables["Question"].Columns["id"], ds.Tables["Possible_Answer"].Columns["questionID"]));
29
30 DataRow dr = ds.Tables["SurveyTemplate"].NewRow();
31 dr["name"] = o[0];
32 dr["description"] = o[1];
33 dr["active"] = 1;
34 ds.Tables["SurveyTemplate"].Rows.Add(dr);
35
36 DataRow dr1 = ds.Tables["Question"].NewRow();
37 dr1["questionIndex"] = 1;
38 dr1["questionContent"] = "q1";
39 dr1.SetParentRow(dr);
40 ds.Tables["Question"].Rows.Add(dr1);
41
42 DataRow dr2 = ds.Tables["Possible_Answer"].NewRow();
43 dr2["answerIndex"] = 1;
44 dr2["answerContent"] = "a11";
45 dr2.SetParentRow(dr1);
46 ds.Tables["Possible_Answer"].Rows.Add(dr2);
47
48 dr1 = ds.Tables["Question"].NewRow();
49 dr1["questionIndex"] = 2;
50 dr1["questionContent"] = "q2";
51 dr1.SetParentRow(dr);
52 ds.Tables["Question"].Rows.Add(dr1);
53
54 dr2 = ds.Tables["Possible_Answer"].NewRow();
55 dr2["answerIndex"] = 1;
56 dr2["answerContent"] = "a21";
57 dr2.SetParentRow(dr1);
58 ds.Tables["Possible_Answer"].Rows.Add(dr2);
59
60 dr2 = ds.Tables["Possible_Answer"].NewRow();
61 dr2["answerIndex"] = 2;
62 dr2["answerContent"] = "a22";
63 dr2.SetParentRow(dr1);
64 ds.Tables["Possible_Answer"].Rows.Add(dr2);
65
66 myCommand1.Update(ds,"SurveyTemplate");
67 myCommand2.Update(ds, "Question");
68 myCommand3.Update(ds, "Possible_Answer");
69 ds.AcceptChanges();
70

and that causes (at line 67):"The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Question_SurveyTemplate". The conflict occurred in database
"ankietyzacja", table "dbo.SurveyTemplate", column
'id'.
The statement has been terminated.
at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.Update(DataSet dataSet, String srcTable)
at AnkietyzacjaWebService.Service1.createSurveyTemplate(Object[] o) in J:\PL\PAI\AnkietyzacjaWebService\AnkietyzacjaWebServicece\Service1.asmx.cs:line 397"


Could You please tell me what am I missing here ?
Thanks a lot.
 

View 5 Replies View Related

Interaction Between Instead Of Insert Trigger And Output Clause Of Insert Statement

Jan 14, 2008


This problem is being seen on SQL 2005 SP2 + cumulative update 4

I am currently successfully using the output clause of an insert statement to return the identity values for inserted rows into a table variable

I now need to add an "instead of insert" trigger to the table that is the subject of the insert.

As soon as I add the "instead of insert" trigger, the output clause on the insert statement does not return any data - although the insert completes successfully. As a result I am not able to obtain the identities of the inserted rows

Note that @@identity would return the correct value in the test repro below - but this is not a viable option as the table in question will be merge replicated and @@identity will return the identity value of a replication metadata table rather than the identity of the row inserted into my_table

Note also that in the test repro, the "instead of insert" trigger actually does nothing apart from the default insert, but the real world trigger has additional code.

To run the repro below - select each of the sections below in turn and execute them
1) Create the table
2) Create the trigger
3) Do the insert - note that table variable contains a row with column value zero - it should contain the @@identity value
4) Drop the trigger
5) Re-run the insert from 3) - note that table variable is now correctly populated with the @@identity value in the row

I need the behaviour to be correct when the trigger is present

Any thoughts would be much appreciated

aero1


/************************************************
1) - Create the table
************************************************/
CREATE TABLE [dbo].[my_table](
[my_table_id] [bigint] IDENTITY(1,1) NOT NULL,
[forename] [varchar](100) NULL,
[surname] [varchar](50) NULL,
CONSTRAINT [pk_my_table] PRIMARY KEY NONCLUSTERED
(
[my_table_id] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, FILLFACTOR = 70) ON [PRIMARY]
)

GO
/************************************************
2) - Create the trigger
************************************************/
CREATE TRIGGER [dbo].[trig_my_table__instead_insert] ON [dbo].[my_table]
INSTEAD OF INSERT
AS
BEGIN

INSERT INTO my_table
(
forename,
surname)
SELECT
forename,
surname
FROM inserted

END

/************************************************
3) - Do the insert
************************************************/

DECLARE @my_insert TABLE( my_table_id bigint )

declare @forename VARCHAR(100)
declare @surname VARCHAR(50)

set @forename = N'john'
set @surname = N'smith'

INSERT INTO my_table (
forename
, surname
)
OUTPUT inserted.my_table_id INTO @my_insert
VALUES( @forename
, @surname
)

select @@identity -- expect this value in @my_insert table
select * from @my_insert -- OK value without trigger - zero with trigger

/************************************************
4) - Drop the trigger
************************************************/

drop trigger [dbo].[trig_my_table__instead_insert]
go

/************************************************
5) - Re-run insert from 3)
************************************************/
-- @my_insert now contains row expected with identity of inserted row
-- i.e. OK

View 5 Replies View Related

Problem Inserting Data Into SQL Server 2005 DB From WebForm Controls

Mar 30, 2007

Hello all,
I am having problems running a stored proc from an aspx.cs file. Basically I want to extract data from webForm controls and create a new record in a DB table. I have watched the "Getting Started" videos on thi site, and the only difference between my code and the code of the demonstrator is the connection string.   My conn string:- dataSrc.ConnectionString = ConfigurationManager.ConnectionStrings["ProjectTblConnString"].ConnectionString;Demonstrator conn string:- dataSrc.ConnectionString = ConfigurationManager.ConnectionStrings("ProjectTblConnString");When I debug with the string as shown by the demonstrator the error list reports that ConnectionStrings is a property and I am trying to use it as a mothod, which is fair enough, but I am just confused as how it worked for the demonstrator and not myself. When I debug with the code I used above I get no error, but nothing is inserted in the DB.Also, it looks as if the only class in my aspx.cs file that is actually being executed is PageLoad() - the remainder of the code seems to be ignored. Below is the entired aspx.cs file:- 1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Collections;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.WebControls;
9 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;
11
12 public partial class CreateProject : System.Web.UI.Page
13 {
14 protected void Page_Load(object sender, EventArgs e)
15 {
16
17 if (User.Identity.IsAuthenticated == false)
18 {
19 Server.Transfer("Default.aspx");
20 }
21
22 if (chkbox_startDate.Checked == true)
23 {
24 txtbox_startDate.ReadOnly = true;
25 txtbox_startDate.Text = (System.DateTime.Now.ToString());
26 }
27
28 }
29
30 protected void btn_create_Click(object sender, EventArgs e)
31 {
32 //connection string for connecting to SQL Server DB
33 SqlDataSource dataSrc = new SqlDataSource();
34 dataSrc.ConnectionString = ConfigurationManager.ConnectionStrings["ProjectTblConnString"].ConnectionString;
35
36
37 //insert data in table using the CreateNewProject stored proc in the DB
38 dataSrc.InsertCommandType = SqlDataSourceCommandType.StoredProcedure;
39 dataSrc.InsertCommand = "CreateNewProject";
40 dataSrc.InsertParameters.Add("Project_Title", txtbox_title.ToString() );
41 dataSrc.InsertParameters.Add("Description", txtbox_desc.ToString() );
42 dataSrc.InsertParameters.Add("Start_Date", txtbox_startDate.ToString() );
43 dataSrc.InsertParameters.Add("Primary_Dev_Lang", list_devLang.ToString() );
44 dataSrc.InsertParameters.Add("Dev_Environment", list_devEnv.ToString() );
45 dataSrc.InsertParameters.Add("No_Junior_Devs", txtbox_juniorDevs.ToString() );
46 dataSrc.InsertParameters.Add("No_Senior_Devs", txtbox_seniorDevs.ToString() );
47
48 int rowsAffected = 0;
49 try
50 {
51 rowsAffected = dataSrc.Insert();
52 }
53 catch (Exception ex)
54 {
55 Server.Transfer(Error.aspx);
56 }
57 finally
58 {
59 dataSrc = null;
60 }
61
62 if (rowsAffected != 1)
63 {
64 label_confirm.Text = "Error, Contact system admin";
65 }
66 else
67 {
68 label_confirm.Text = "Success";
69 }
70
71 }//end btn_create
72
73 //if cancel is clicked set all values back to default
74 protected void btn_cancel_Click(object sender, EventArgs e)
75 {
76 txtbox_title.Text = "";
77 txtbox_desc.Text = "";
78 txtbox_startDate.Text = "";
79 txtbox_seniorDevs.Text = "";
80 txtbox_juniorDevs.Text = "";
81 list_devEnv.SelectedIndex = 0;
82 list_devLang.SelectedIndex = 0;
83 chkbox_startDate.Checked = true;
84 label_confirm.Text = "";
85 }
86
87 //if checked the current dateTime is inserted into txtbox
88 protected void chkbox_startDate_CheckedChanged(object sender, EventArgs e)
89 {
90 if (chkbox_startDate.Checked == true)
91 {
92 txtbox_startDate.ReadOnly = true;
93 txtbox_startDate.Text = (System.DateTime.Now.ToString());
94 }
95 else
96 {
97 txtbox_startDate.ReadOnly = false;
98 txtbox_startDate.Text = "";
99 }
100 }//end chkox
101
102
103 }//end class
 
Any help anyome can give is greatly appreciated. This is part of my Final Year College Dissertation which is due in 3wks !!!!
Sláinte á chaire,
Seán
 

View 2 Replies View Related

Form Based Authentication + Webform Report Viewer Control

Nov 19, 2007



Hi,
I would like to know how to call a report from a report viewer control in a web application. The reporting services is forms authenticated. I've done this authentication using the sample solution given by microsoft (adding custom security extension). Now am able to view the reports from Report manager and Report server URL. But i dont know how to authenticate the user from my web application and pass the credentials to the report server to view the report in report viewer control. Can somebody help in this? its bit urgent. Thanks in advance

View 1 Replies View Related

Can&#39;t Query More Than 15 Fields In A Select Statement

Jul 14, 1999

An ADODB error spawn everytime I query more than 15 fields in a specific SQL Table. My sql statement is something like this:

set rs=server.createobject("ADODB.Recordset")
rs.open "select * from mytbl",application("mycon"),1,3

And the error is something like this:

"you can't query more than the maximum field "

View 1 Replies View Related

Convert Fields In Select Statement

Oct 31, 2006

The data I have has a 1 in for each Yes answer and a 2 for each no answer. I just want the select statement to show the word yes when there's a 1 and the word no when there's a 2. I don't need to update or change the database. Could anyone lead me in the right direction here? Thanks

View 4 Replies View Related

Excluding Fields In SELECT Statement

Oct 23, 2005

Hi,Is there a way to exclude fields in a query other than just includingthe ones you want. If there are 20 fields and you want to see all but3, it would be a lot easier to exclude the 3.Thanks

View 8 Replies View Related

SELECT Statement For Fields That Are Blank?

Jan 9, 2008

I thought this was working, but apparently it was not. I was wondering how I would create a SELECT Statement for values that are blank (Equal to ""). I really could have swore that this was working, but I guess it wasn't.

Here is my code:





Code Block

try
{
string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Environment.CurrentDirectory + @"MyDB.accdb;Jet OLEDB:Database Password=MyPassword;";

// create an open the connection
OleDbConnection conn = new OleDbConnection(conString);
OleDbCommand command = new OleDbCommand();
command = conn.CreateCommand();

// create the DataSet
DataSet ds = new DataSet();

// run the query
command.CommandText = "SELECT ID AS [#], Company AS [Company], FName AS [First Name], LName AS [Last Name], Type AS [Type] FROM Table1 WHERE Tags = @P0;";
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter = new OleDbDataAdapter(command);
command.Parameters.Add("@P0", OleDbType.VarChar).Value = "";
adapter.Fill(ds);

// close the connection
conn.Close();

bindingSource1.DataSource = ds.Tables[0];

DataGridView.DataSource = bindingSource1;

// set the size of the dataGridView Columns
this.DataGridView.Columns[0].Visible = false;
this.DataGridView.Columns[1].Width = 234;
this.DataGridView.Columns[2].Width = 50;
this.DataGridView.Columns[3].Width = 50;
this.DataGridView.Columns[4].Width = 75;

//Sort on the Title Column
DataGridViewColumn sortColumn = DataGridView.Columns[1];
ListSortDirection direction;
direction = ListSortDirection.Ascending;
DataGridView.Sort(sortColumn, direction);

//Set the Selected Property of the First Row to False
DataGridView.Rows[0].Selected = false;
}
catch
{
}

Thank you again for your help.

View 8 Replies View Related

Book Refer

Oct 22, 2005

Hi

I am new to SQL2000 and also in RDBMS.

Pls suggesst the book which is helpful for me.


Thanks...

asm

View 6 Replies View Related

Case Statement Error In An Insert Statement

May 26, 2006

Hi All,
I've looked through the forum hoping I'm not the only one with this issue but alas, I have found nothing so I'm hoping someone out there will give me some assistance.
My problem is the case statement in my Insert Statement. My overall goal is to insert records from one table to another. But I need to be able to assign a specific value to the incoming data and thought the case statement would be the best way of doing it. I must be doing something wrong but I can't seem to see it.

Here is my code:
Insert into myTblA
(TblA_ID,
mycasefield =
case
when mycasefield = 1 then 99861
when mycasefield = 2 then 99862
when mycasefield = 3 then 99863
when mycasefield = 4 then 99864
when mycasefield = 5 then 99865
when mycasefield = 6 then 99866
when mycasefield = 7 then 99867
when mycasefield = 8 then 99868
when mycasefield = 9 then 99855
when mycasefield = 10 then 99839
end,
alt_min,
alt_max,
longitude,
latitude
(
Select MTB.LocationID
MTB.model_ID
MTB.elevation, --alt min
null, --alt max
MTB.longitude, --longitude
MTB.latitude --latitude
from MyTblB MTB
);

The error I'm getting is:
Incorrect syntax near '='.

I have tried various versions of the case statement based on examples I have found but nothing works.
I would greatly appreciate any assistance with this one. I've been smacking my head against the wall for awhile trying to find a solution.

View 10 Replies View Related

How To Use Select Statement Inside Insert Statement

Oct 20, 2014

In the below code i want to use select statement for getting customer

address1,customeraddress2,customerphone,customercity,customerstate,customercountry,customerfirstname,customerlastname

from customer table.Rest of the things will be as it is in the following code.How do i do this?

INSERT INTO EMImportListing ("
sql += " CustId,Title,Description,JobCity,JobState,JobPostalCode,JobCountry,URL,Requirements, "
sql += " IsDraft,IsFeatured,IsApproved,"
sql += " Email,OrgName,customerAddress1,customerAddress2,customerCity,customerState,customerPostalCode,

[code]....

View 1 Replies View Related

SQL Statement For Querying Data With Dynamic Fields

Sep 19, 2006

I am working on a project in which a customer wants to be able to list and search their inventory and display the items in a table/grid on a web page.Each item in their inventory has a set of properties - for example, manufacturer, price, serial number, name, etc.  The complicated part is that they want an admin to be able to modify/add/delete the set of properties.  So for example, they could add the attribute "size."   Given that, I think what is needed is 3 tables - one to store the set of properties schema, one for the items, and one to store the actual properties for each item.  I know i COULD use alter table statements to add and delete columns, but that doesn't seem like the "right" solution.I would like to be able to write a query such that each row returns the item and all its properties - then i can easily bind to a datagrid.  However, what would the query be to do this?  I also need to be able to allow the customer to query for items with certain properties - i imagine the sql for that to be similar to this:SELECT * FROM items d WHERE d.Id IN(SELECT a.ItemId FROM attributes a WHERE a.Name = "Manufacturer" AND a.Value = "Samsung") AND d.Id IN(SELECT a.ItemId FROM attributes a WHERE a.Name = "SerialNumber" AND a.Value = "3223")

View 1 Replies View Related

Combine Fields And Text In Select Statement

Jan 1, 2007

Is it possible to combine fields and text in a select statement?
In a dropDownList I want to show a combination of two different fields, and have the value of the selected item come from a third field. So, I thought I could maybe do something like this:
  SELECT DISTINCT GRP AS GroupName, "Year: " + YEAR + "Grade: " + GRD AS ShowMe
FROM GE_Data
WHERE (DIST = @DIST) 
 
I hoped that would take the values in YEAR and GRD and concatenate them with the other text. Then my dropDownList could show the ShowMe value and have the GroupName as the value it passes on. However, when I test this in the VS Query Builder, it says that Year and Grade are unknown column names and changes the double-quotes to square brackets.
If this is possible, or there's a better way to do it, I'd love some more info.
Thanks!
-Mathminded

View 7 Replies View Related

SELECT Statement With 2 Columns Originating From The Same Fields

Jul 19, 2006

Hello,

I've been busy all night searching and reading trying to figure out how I can do the following.

I have a table that tracks user IDs in multiple fields. When I select records from this table I need a way to resolve those ID fields back into user names by referencing the users table. SQL statement thus far...

SELECT A.Username as NameA, B.Username As NameB, FROM theTable, Users As A, Users As B WHERE theTable.UserIDA ???

How do I resolve theTable.UserIDA and theTable.UserIDB back to Users.Username so that the records returned fill the fields NameA and NameB?

Your help is greatly appreciated.

Thanks,

-Mike
Ontario, Canada

View 5 Replies View Related

Problem With Null Fields And Case Statement

Jul 21, 2004

Can someone help me with this :

Case WHEN ISNULL (dbo.BLH.n1name,'NOTHING')= 'NOTHING' then dbo.BLH.coname else dbo.BLH.n1name End as CustName

as the strored proc is not returning value when the fileds is blank

cheers

View 2 Replies View Related

SELECT Statement To Display Combined Fields

Oct 17, 2004

Dear All
I am trying to populate an OledbDatareader for binding to a ASP datagrid.

For this I use select statement to display combined fields in a datagrid cell.
Eg. Select (Field1+ '<br/>' + Field2 + '<br/>' + Field 3) As Address .. and so on.
But the problem is if any of the three field is null the combined field 'Address' returns as Null.
Please help me to overcome this problem.

Regards
kalanad ( beginner)

View 12 Replies View Related

UPDATE Statement Creating NULL Fields?

Oct 23, 2014

I am attempting to update a table that drives a report. The report is at the order level. An order can have several types of demand (revenue $): Ship and/or Backordered. When I update one of these demand fields on the report table, I would expect those orders that have that type of demand to update, and those orders that don't have that type of demand to remain at their current value ($0 in this example which is the table default). But what is happening is that orders that don't have that type of demand are changing to NULL. What am i doing wrong with my update statement that is causing this?

Code:
CREATE TABLE #sales(
OrdNo int,
StatusGrp varchar(10),
Demand decimal(10,2)
)
INSERT INTO #sales
VALUES (1,'Ship',100.00)

[Code] .....

View 6 Replies View Related

T-SQL (SS2K8) :: Updating Statement Depending On 2 Fields

Sep 30, 2015

I need to build an update query for all my article beginning with '0.%' for my varchar field refkey, but depending on some conditions.

For example.
Case st.base <> '' and st.qttbase <> 0
Theo refkey = B
Case st.cos <>'' and st.qttcos <> 0
Then refkey = C
Case st.refo <> '' and st.qttrefo <> 0
Then refkey = R

But my problem are That i can have Many combination on refkey, for example:

B,BC,BCR,C,CB,CBR,R...and so on.

Also i need to separate the letters with comma, like:

B
B,C
B,C,R
.....

View 6 Replies View Related

Controlling Fields In A Select Statement By Use Of Parameters

Sep 29, 2005

Hi to allI wish to be able to have a standard select statement which hasadditional fields added to it at run-time based on suppliedparameter(s).iedeclare @theTest1 nvarchar(10)set @theTest1='TRUE'declare @theTest2 nvarchar(10)set @theTest2='TRUE'selectp_full_nameif @theTest1='TRUE'BEGINother field1,ENDif @theTest2='TRUE'BEGINother field2ENDfrom dbo.tbl_GIS_personwhere record_id < 20I do not wish to use an IF statement to test the parameter for acondition and then repeat the entire select statement particularly asit is a UNIONed query for three different statementiedeclare @theTest1 nvarchar(10)set @theTest1='TRUE'declare @theTest2 nvarchar(10)set @theTest2='TRUE'if @theTest1='TRUE' AND @theTest2='TRUE'BEGINselectp_full_name,other field1,other field2from dbo.tbl_GIS_personwhere record_id < 20ENDif @theTest1='TRUE' AND @theTest2='FALSE'BEGINselectp_full_name,other field1from dbo.tbl_GIS_personwhere record_id < 20END......if @theTest<>'TRUE'BEGINselectp_full_namefrom dbo.tbl_GIS_personwhere record_id < 20ENDMake sense? So the select is standard in the most part but with smallvariations depending on the user's choice. I want to avoid risk ofbreakage by having only one spot that the FROM, JOIN and WHEREstatements need to be defined.The query will end up being used in an XML template query.Any help would be much appreciatedRegardsGIS Analyst

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved