Showing posts with label row. Show all posts
Showing posts with label row. Show all posts

Tuesday, March 27, 2012

Adding a new row to SQL table

Hi all,

I have a database setup with a few rows and i would like to allow a user to create a new row of data. After some googling, I've deduced that I need to somehow use an onclick command to perform an insert command. here is my code as of right now:

protectedvoid ItemAdd_Click(object sender,EventArgs e)

{

int newnum = 4;int POnum = newnum ++;

string Item = textbox3.Text.ToString();

string Quantity = textbox4.ToString();

string Part = textbox5.ToString();

string Description = textbox6.Text.ToString();

string Price = textbox7.Text.ToString();string UOM = textbox8.Text.ToString();

SqlDataSource2.InsertParameters.Clear();

SqlDataSource2.InsertParameters.Add("@.Item", Item);

SqlDataSource2.InsertParameters.Add("@.Quantity", Quantity);

SqlDataSource2.InsertParameters.Add("@.Part", Part);

SqlDataSource2.InsertParameters.Add("@.Description", Description);

SqlDataSource2.InsertParameters.Add("@.Price", Price);

SqlDataSource2.InsertParameters.Add("@.UOM", UOM);

SqlDataSource1.InsertCommand ="insert into ItemMaster "+

"values (12, @.Item, @.Quantity, @.Part, @.Description, @.Price, @.UOM)";

SqlDataSource2.Insert();

}

here's the aspx:

<%@.PageLanguage="C#"MasterPageFile="~/MasterPage.master"AutoEventWireup="true"CodeFile="createpo.aspx.cs"Inherits="Subpgs_Purchasing_createpo"Title="Create A PO" %>

<asp:ContentID="Content1"ContentPlaceHolderID="ContentPlaceHolder1"Runat="Server">

<tablestyle="width: 600px; position: relative; top: 30px; height: 253px"cellpadding="10px">

<tr>

<tdstyle="width: 180px; text-align: left;"rowspan="2">

Select Vendor<br/>- or -<br/><asp:LinkButtonID="Linkbutton1"runat="server"OnClick="Linkbutton1_Click">Create Vendor</asp:LinkButton></td>

<tdstyle="width: 100px"rowspan="2">

<asp:ListBoxID="ListBox2"runat="server"DataSourceID="SqlDataSource1"DataTextField="Name"

DataValueField="ID"OnSelectedIndexChanged="ListBox2_SelectedIndexChanged"></asp:ListBox><asp:SqlDataSourceID="SqlDataSource1"runat="server"

ConnectionString="<%$ ConnectionStrings:ConnectionString %>"SelectCommand="SELECT * FROM [Vendor_info]"></asp:SqlDataSource>

</td>

<tdstyle="width: 180px; text-align: left;">

Job/Req.S.O. No.</td>

<tdstyle="width: 100px">

<asp:TextBoxID="Job"runat="server"></asp:TextBox></td>

</tr>

<tr>

<tdstyle="width: 180px; text-align: left;">

Terms</td>

<tdstyle="width: 100px">

<asp:TextBoxID="Terms"runat="server"></asp:TextBox></td>

</tr>

<tr>

<tdstyle="width: 180px; text-align: left;">

F.O.B.</td>

<tdstyle="width: 100px">

<asp:TextBoxID="FOB"runat="server"></asp:TextBox></td>

<tdstyle="width: 180px; text-align: left;">

Ship To:<br/>

Address:<br/>

City / State / Zip:</td>

<tdstyle="width: 100px">

<asp:TextBoxID="Ship1"runat="server"></asp:TextBox>

<asp:TextBoxID="Ship2"runat="server"></asp:TextBox>

<asp:TextBoxID="Ship3"runat="server"></asp:TextBox></td>

</tr>

</table>

<br/>

<br/>

<asp:SqlDataSourceID="SqlDataSource2"runat="server"ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Purchase_Orders.mdf;Integrated Security=True;User Instance=True;Context Connection=False"

ProviderName="System.Data.SqlClient"SelectCommand="SELECT [Item], [Quantity], [Part], [Description], [Price], [UOM], [Ammount], [PONumber] FROM [ItemMaster]"DeleteCommand="DELETE FROM [ItemMaster] WHERE [PONumber] = @.PONumber"InsertCommand="INSERT INTO [ItemMaster] ([Item], [Quantity], [Part], [Description], [Price], [UOM], [Ammount], [PONumber]) VALUES (@.Item, @.Quantity, @.Part, @.Description, @.Price, @.UOM, @.Ammount, @.PONumber)"UpdateCommand="UPDATE [ItemMaster] SET [Item] = @.Item, [Quantity] = @.Quantity, [Part] = @.Part, [Description] = @.Description, [Price] = @.Price, [UOM] = @.UOM, [Ammount] = @.Ammount WHERE [PONumber] = @.PONumber">

<DeleteParameters>

<asp:ParameterName="PONumber"Type="Decimal"/>

</DeleteParameters>

<UpdateParameters>

<asp:ParameterName="Item"Type="String"/>

<asp:ParameterName="Quantity"Type="Decimal"/>

<asp:ParameterName="Part"Type="String"/>

<asp:ParameterName="Description"Type="String"/>

<asp:ParameterName="Price"Type="Decimal"/>

<asp:ParameterName="UOM"Type="String"/>

<asp:ParameterName="Ammount"Type="Decimal"/>

<asp:ParameterName="PONumber"Type="Decimal"/>

</UpdateParameters>

<InsertParameters>

<asp:ParameterName="Item"Type="String"/>

<asp:ParameterName="Quantity"Type="Decimal"/>

<asp:ParameterName="Part"Type="String"/>

<asp:ParameterName="Description"Type="String"/>

<asp:ParameterName="Price"Type="Decimal"/>

<asp:ParameterName="UOM"Type="String"/>

<asp:ParameterName="Ammount"Type="Decimal"/>

<asp:ParameterName="PONumber"Type="Decimal"/>

</InsertParameters>

</asp:SqlDataSource>

<br/>

<table>

<tr>

<td>Item #</td>

<td><asp:TextBoxID="textbox3"runat=server></asp:TextBox></td>

<td>Quantity</td>

<td><asp:TextBoxID="textbox4"runat=server></asp:TextBox></td>

<td>Part Number</td>

<td><asp:TextBoxID="textbox5"runat=server></asp:TextBox></td>

</tr>

<tr>

<td>Description</td>

<td><asp:TextBoxID="textbox6"runat=server></asp:TextBox></td>

<td>Unit Price</td>

<td><asp:TextBoxID="textbox7"runat=server></asp:TextBox></td>

<td>Unit of Measure</td>

<td><asp:TextBoxID="textbox8"runat=server></asp:TextBox></td>

</tr>

<tr>

<tdcolspan="6"align="center"><asp:ButtonID="ItemAdd"runat=servertext="Add Item"OnClick="ItemAdd_Click"/></td>

</tr>

</table>

<br/>

<br/>

<asp:GridViewID="GridView1"runat="server"AutoGenerateColumns="False"DataKeyNames="PONumber"

DataSourceID="SqlDataSource2">

<Columns>

<asp:CommandFieldShowEditButton="True"/>

<asp:BoundFieldDataField="Item"HeaderText="Item"SortExpression="Item"/>

<asp:BoundFieldDataField="Quantity"HeaderText="Quantity"SortExpression="Quantity"/>

<asp:BoundFieldDataField="Part"HeaderText="Part"SortExpression="Part"/>

<asp:BoundFieldDataField="Description"HeaderText="Description"SortExpression="Description"/>

<asp:BoundFieldDataField="Price"HeaderText="Price"SortExpression="Price"/>

<asp:BoundFieldDataField="UOM"HeaderText="UOM"SortExpression="UOM"/>

<asp:BoundFieldDataField="Ammount"HeaderText="Ammount"SortExpression="Ammount"/>

<asp:BoundFieldDataField="PONumber"HeaderText="PONumber"ReadOnly="True"SortExpression="PONumber"

Visible="False"/>

</Columns>

</asp:GridView>

<br/>

<br/>

<br/>

<asp:ButtonID="Button1"runat="server"Text="Submit Data"OnClick="Button1_Click"/> <br/>

<br/>

<asp:LabelID="Label1"runat="server"Text="Please Verify Information below!"Visible="False"></asp:Label><br/>

<br/>

<tablealign="left">

<tr>

<tdstyle="width: 200px; text-align: left;">

<asp:LabelID="Label4"runat="server"Text="Job/REQ.S.O. No."Visible="false"></asp:Label></td>

<tdstyle="width: 200px; text-align: left;">

<asp:LabelID="Label5"runat="server"></asp:Label></td>

</tr>

<tr>

<tdstyle="width: 200px; text-align: left;">

<asp:LabelID="Label7"runat="server"Text="Terms"Visible="false"></asp:Label></td>

<tdstyle="width: 200px; text-align: left;">

<asp:LabelID="Label8"runat="server"></asp:Label></td>

</tr>

<tr>

<tdstyle="width: 200px; text-align: left;">

<asp:LabelID="Label10"runat="server"Text="F.O.B."Visible="false"></asp:Label></td>

<tdstyle="width: 200px; text-align: left;">

<asp:LabelID="Label11"runat="server"></asp:Label></td>

</tr>

</table>

<asp:DetailsViewID="DetailsView1"runat="server"AutoGenerateRows="False"DataSourceID="SqlDataSource1"

Height="50px"Visible="False"Width="260px"BackColor="#CCCCCC"BorderColor="#999999"BorderStyle="Solid"BorderWidth="3px"CellPadding="4"CellSpacing="2"DataKeyNames="ID"ForeColor="Black">

<FooterStyleBackColor="#CCCCCC"/>

<EditRowStyleBackColor="#000099"Font-Bold="True"ForeColor="White"/>

<RowStyleBackColor="White"/>

<PagerStyleBackColor="#CCCCCC"ForeColor="Black"HorizontalAlign="Left"/>

<Fields>

<asp:BoundFieldDataField="ID"HeaderText="ID"ReadOnly="True"SortExpression="ID"/>

<asp:BoundFieldDataField="Name"HeaderText="Name"SortExpression="Name"/>

<asp:BoundFieldDataField="Street"HeaderText="Street"SortExpression="Street"/>

<asp:BoundFieldDataField="City"HeaderText="City"SortExpression="City"/>

<asp:BoundFieldDataField="State"HeaderText="State"SortExpression="State"/>

<asp:BoundFieldDataField="Zip"HeaderText="Zip"SortExpression="Zip"/>

<asp:BoundFieldDataField="Telephone Number"HeaderText="Telephone Number"SortExpression="Telephone Number"/>

<asp:BoundFieldDataField="Contact Information"HeaderText="Contact Information"

SortExpression="Contact Information"/>

<asp:BoundFieldDataField="E-mail address"HeaderText="E-mail address"SortExpression="E-mail address"/>

<asp:BoundFieldDataField="Fax Number"HeaderText="Fax Number"SortExpression="Fax Number"/>

<asp:BoundFieldDataField="Comments"HeaderText="Comments"SortExpression="Comments"/>

</Fields>

<HeaderStyleBackColor="Black"Font-Bold="True"ForeColor="White"/>

</asp:DetailsView>

<br/>

<br/>

<br/>

<asp:ButtonID="Button2"runat="server"Text="E-Mail PO"Visible="False"OnClick="Button2_Click"/>

</asp:Content>

whenever I run this, I receive the following error and am not sure how to correct it:

System.Data.SqlClient.SqlException: Must declare the scalar variable "@.Item".

If someone could please explain to me the process here of what is going ion it would be greatly appreciated. My understanding is the @.item is just a variable if you will so i'm not sure why its stating i need to declare it.

Thank you all!

Welcome to the community. I would suggest you use the InsertCode option to insert code in your posts from next time. Lets start from the starting and then we will remove errors as we go.

Gizm0:

string Item = textbox3.Text.ToString();

string Quantity = textbox4.ToString();

string Part = textbox5.ToString();

I am assuming these are your textboxes. You should use Text property of textboxes like you used for others. Also, you don't have to use ToString() method. Text property returns the textbox value as a string.

|||

Hi Bullpit.

Sorry about that, I didn't see the code Icon there. Anyhow, I made the changes and continue to receive the same error. At first glance, does it at least look like i'm on the right path? I've always been more hardware/network inclined so a lot of the google searches and forums I used to piece this together are still Greek to me.

Thanks for the response!

|||

I don't use SqlDataSource as such. Since you are writing some code, you can instead use this code to insert values to your database. Extend this example to add more parameters.

protected void ItemAdd_Click(object sender, EventArgs e) {// connection string to your database SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");// open connection mySqlConnection.Open();// create command object to execute query SqlCommand mySqlCommand = mySqlConnection.CreateCommand();// set command text to the INSERT sql query mySqlCommand.CommandText = @."INSERT INTO Employee (Item, Quantity, Part...) VALUES( @.Item, @.Quantity, @.Part...)";// Add parameters mySqlCommand.Parameters.Add("@.Item", SqlDbType.VarChar); mySqlCommand.Parameters.Add("@.Quantity", SqlDbType.VarChar); mySqlCommand.Parameters.Add("@.Part", SqlDbType.VarChar);// set parameter values mySqlCommand.Parameters["@.Item"].Value = textbox3.Text; mySqlCommand.Parameters["@.Quantity"].Value = textbox4.Text; mySqlCommand.Parameters["@.Part"].Value = textbox5.Text;// execute query mySqlCommand.ExecuteNonQuery();// close connection mySqlConnection.Close();}

You will need these namespaces.

using System.Data;
using System.Data.SqlClient;

|||

Hey BullPit,

I really appreciate the help! I was able to get this working using your code above. Now it looks like I just need to validate the input boxes to make sure the correct data is being entered in the fields.

Again, thanks!

sql

adding a new data column (not derived) midway thru a data flow

I need to know what a table's max row Identity is part way thru a data flow. I can't get it at the beginning of the data flow. I need to either (1) add it to the data buffer part way thru or (2) set it into a package variable and then reference the var in a script component.

I've not found a way to add a database column to the data buffer without doing a lookup for each row (too slow and not appropriate here) or some goofy oledb source and then merge join into the data buffer on a contrived join.

I've read questions about referencing package vars in scripts but I can't get that to work. DTS.Variables("varname").Value isn't recognised when I code it up.

Anyone have an idea or solution for either one of these? If you're gonna explain the script code, please include the entire snipet including the INCLUDEs, etc.

While I am not convinced that the MergeJoin is contrived or the oledb source is goofy you should check to see that the variable varname is in the ReadOnlyVariables property of the script component. If it isn't then add it and then the DTS.Variables("varname").Value should work. If it is then can you provide the error you are receiving.

Thanks,

Matt

|||

Matt,

I wasn't saying that the MergeJoin is contrived or that the OLEDB source is goofy, I was saying that the way I'd be using them to solve my dilema is. I have used both of these controls and am happy with them, but they aren't what I'd like to use to solve this problem.

Regarding the scripting problem, I have put varname in the ReadOnlyVariables property. In the script window when I enter DTS.Variables("varname").Value the interpreter places the squigly underline under DTS and says that "Name 'DTS' is not declared". There is no intelisense when I type the period between DTS & Variables. So I'm thinking that something needs to be declared. Here's my code:

Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

Public Class ScriptMain
Inherits UserComponent
Dim counter As Integer
Dim FirstTime As Boolean

Public Sub New() 'This method gets called only once per execution
FirstTime = True
End Sub

Public Overrides Sub Input_ProcessInputRow(ByVal Row As InputBuffer)
If FirstTime Then
counter = Row.MaxRowId
FirstTime = False
End If
counter = dts.variables("dataset").value 'dts not recognized
Row.SubCntrctId = counter
End Sub
End Class

|||

Gordon,

The syntax for accessing variables in the script component is different from in the script task. The syntax is:

Me.Variables.<var-name>|||Somebody would want to tell the boys in Wrox about this... their

chapter on scripting is very light on the differences between Task and

Component...

They only mention variables in relation to the script task... so you

(ok, well.. I, at least . ) end up supposing that, since no one

mentioned otherwise, the variable access must be the same in a

script component... sigh...

But, thankfully, we have good ole Jamie to set us straight...

Thanks Jamie,

PJ|||

Gordon, I know what you mean -- I'm facing the same problem in SSIS Designer. Usually I work around it in the data source, doing an explicit join right off the bat to get the extra column with the needed value. But now I have a case where the data source is a flat file but the value needed for the extra column is still determined by a SQL select statement (and still independent of the rows in the primary data source).

So I've got a multi-row, multi-column data stream X and a single-row, single-column data stream Y. There should be a simple way in SSIS Designer to (outer) join them (i.e. with no condition):

select X.x1, X.x2, Y.y1 from X, Y

But all the Merge/Join/Lookup etc. data flow transformations require (as you said) join columns to be identified.

This could be done with the Derived Column transformation, except that its expression cannot be a SQL statement and it doesn't need to be evaluated it for every row of X anyway. Which leads me to a similar conclusion as you: that since a variable could be used in the expression, the result of the query should be saved in a variable. But in SSIS Designer, a variable (in this case, scoped to the data flow task) cannot be specified as an SQL statement.

Help! What is the best practice in this situation?

|||

Kevin,

Your request is basically to be able to do an OUTER JOIN. Is that correct?

I have lamented the lack of an OUTER JOIN component in the past and have requested one for future versions. Unfortunately I did that during beta and that request hasn't made it through to Microsoft Connect. Can I suggest that you go to Microsoft Connect and put in a request for it and then put a link to it up here so that I can vote for it.

If you dont ask then you won't get!

The only way to accomplish what you need in ths instance is to use a script component.

-Jamie

|||

Hello all

There are two ways I could find to tackle this problem.

1) This is very slow and consumes a lot of memory

create a dummy derived column in both tables you want to join and insert a dummy 1(you may need to sort on this column which is the real performance killer). Then use merge join on this field so resulting new table contains the new column coming from the other rowset.

2) Split the DataFlow task into several pieces. Populate a variable (I am assuming the value you want to add as the new column will come from a rowset of count 1) with the first pass. Then use a derived column to insert the new value using this variable.

I am not sure if these are the recommended ways to do it but they worked for me.

Batu

adding a new data column (not derived) midway thru a data flow

I need to know what a table's max row Identity is part way thru a data flow. I can't get it at the beginning of the data flow. I need to either (1) add it to the data buffer part way thru or (2) set it into a package variable and then reference the var in a script component.

I've not found a way to add a database column to the data buffer without doing a lookup for each row (too slow and not appropriate here) or some goofy oledb source and then merge join into the data buffer on a contrived join.

I've read questions about referencing package vars in scripts but I can't get that to work. DTS.Variables("varname").Value isn't recognised when I code it up.

Anyone have an idea or solution for either one of these? If you're gonna explain the script code, please include the entire snipet including the INCLUDEs, etc.

While I am not convinced that the MergeJoin is contrived or the oledb source is goofy you should check to see that the variable varname is in the ReadOnlyVariables property of the script component. If it isn't then add it and then the DTS.Variables("varname").Value should work. If it is then can you provide the error you are receiving.

Thanks,

Matt

|||

Matt,

I wasn't saying that the MergeJoin is contrived or that the OLEDB source is goofy, I was saying that the way I'd be using them to solve my dilema is. I have used both of these controls and am happy with them, but they aren't what I'd like to use to solve this problem.

Regarding the scripting problem, I have put varname in the ReadOnlyVariables property. In the script window when I enter DTS.Variables("varname").Value the interpreter places the squigly underline under DTS and says that "Name 'DTS' is not declared". There is no intelisense when I type the period between DTS & Variables. So I'm thinking that something needs to be declared. Here's my code:

Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

Public Class ScriptMain
Inherits UserComponent
Dim counter As Integer
Dim FirstTime As Boolean

Public Sub New() 'This method gets called only once per execution
FirstTime = True
End Sub

Public Overrides Sub Input_ProcessInputRow(ByVal Row As InputBuffer)
If FirstTime Then
counter = Row.MaxRowId
FirstTime = False
End If
counter = dts.variables("dataset").value 'dts not recognized
Row.SubCntrctId = counter
End Sub
End Class

|||

Gordon,

The syntax for accessing variables in the script component is different from in the script task. The syntax is:

Me.Variables.<var-name>|||Somebody would want to tell the boys in Wrox about this... their chapter on scripting is very light on the differences between Task and Component...
They only mention variables in relation to the script task... so you (ok, well.. I, at least . ) end up supposing that, since no one mentioned otherwise, the variable access must be the same in a script component... sigh...
But, thankfully, we have good ole Jamie to set us straight...
Thanks Jamie,
PJ
|||

Gordon, I know what you mean -- I'm facing the same problem in SSIS Designer. Usually I work around it in the data source, doing an explicit join right off the bat to get the extra column with the needed value. But now I have a case where the data source is a flat file but the value needed for the extra column is still determined by a SQL select statement (and still independent of the rows in the primary data source).

So I've got a multi-row, multi-column data stream X and a single-row, single-column data stream Y. There should be a simple way in SSIS Designer to (outer) join them (i.e. with no condition):

select X.x1, X.x2, Y.y1 from X, Y

But all the Merge/Join/Lookup etc. data flow transformations require (as you said) join columns to be identified.

This could be done with the Derived Column transformation, except that its expression cannot be a SQL statement and it doesn't need to be evaluated it for every row of X anyway. Which leads me to a similar conclusion as you: that since a variable could be used in the expression, the result of the query should be saved in a variable. But in SSIS Designer, a variable (in this case, scoped to the data flow task) cannot be specified as an SQL statement.

Help! What is the best practice in this situation?

|||

Kevin,

Your request is basically to be able to do an OUTER JOIN. Is that correct?

I have lamented the lack of an OUTER JOIN component in the past and have requested one for future versions. Unfortunately I did that during beta and that request hasn't made it through to Microsoft Connect. Can I suggest that you go to Microsoft Connect and put in a request for it and then put a link to it up here so that I can vote for it.

If you dont ask then you won't get!

The only way to accomplish what you need in ths instance is to use a script component.

-Jamie

|||

Hello all

There are two ways I could find to tackle this problem.

1) This is very slow and consumes a lot of memory

create a dummy derived column in both tables you want to join and insert a dummy 1(you may need to sort on this column which is the real performance killer). Then use merge join on this field so resulting new table contains the new column coming from the other rowset.

2) Split the DataFlow task into several pieces. Populate a variable (I am assuming the value you want to add as the new column will come from a rowset of count 1) with the first pass. Then use a derived column to insert the new value using this variable.

I am not sure if these are the recommended ways to do it but they worked for me.

Batu

adding a new data column (not derived) midway thru a data flow

I need to know what a table's max row Identity is part way thru a data flow. I can't get it at the beginning of the data flow. I need to either (1) add it to the data buffer part way thru or (2) set it into a package variable and then reference the var in a script component.

I've not found a way to add a database column to the data buffer without doing a lookup for each row (too slow and not appropriate here) or some goofy oledb source and then merge join into the data buffer on a contrived join.

I've read questions about referencing package vars in scripts but I can't get that to work. DTS.Variables("varname").Value isn't recognised when I code it up.

Anyone have an idea or solution for either one of these? If you're gonna explain the script code, please include the entire snipet including the INCLUDEs, etc.

While I am not convinced that the MergeJoin is contrived or the oledb source is goofy you should check to see that the variable varname is in the ReadOnlyVariables property of the script component. If it isn't then add it and then the DTS.Variables("varname").Value should work. If it is then can you provide the error you are receiving.

Thanks,

Matt

|||

Matt,

I wasn't saying that the MergeJoin is contrived or that the OLEDB source is goofy, I was saying that the way I'd be using them to solve my dilema is. I have used both of these controls and am happy with them, but they aren't what I'd like to use to solve this problem.

Regarding the scripting problem, I have put varname in the ReadOnlyVariables property. In the script window when I enter DTS.Variables("varname").Value the interpreter places the squigly underline under DTS and says that "Name 'DTS' is not declared". There is no intelisense when I type the period between DTS & Variables. So I'm thinking that something needs to be declared. Here's my code:

Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

Public Class ScriptMain
Inherits UserComponent
Dim counter As Integer
Dim FirstTime As Boolean

Public Sub New() 'This method gets called only once per execution
FirstTime = True
End Sub

Public Overrides Sub Input_ProcessInputRow(ByVal Row As InputBuffer)
If FirstTime Then
counter = Row.MaxRowId
FirstTime = False
End If
counter = dts.variables("dataset").value 'dts not recognized
Row.SubCntrctId = counter
End Sub
End Class

|||

Gordon,

The syntax for accessing variables in the script component is different from in the script task. The syntax is:

Me.Variables.<var-name>|||Somebody would want to tell the boys in Wrox about this... their

chapter on scripting is very light on the differences between Task and

Component...

They only mention variables in relation to the script task... so you

(ok, well.. I, at least . ) end up supposing that, since no one

mentioned otherwise, the variable access must be the same in a

script component... sigh...

But, thankfully, we have good ole Jamie to set us straight...

Thanks Jamie,

PJ|||

Gordon, I know what you mean -- I'm facing the same problem in SSIS Designer. Usually I work around it in the data source, doing an explicit join right off the bat to get the extra column with the needed value. But now I have a case where the data source is a flat file but the value needed for the extra column is still determined by a SQL select statement (and still independent of the rows in the primary data source).

So I've got a multi-row, multi-column data stream X and a single-row, single-column data stream Y. There should be a simple way in SSIS Designer to (outer) join them (i.e. with no condition):

select X.x1, X.x2, Y.y1 from X, Y

But all the Merge/Join/Lookup etc. data flow transformations require (as you said) join columns to be identified.

This could be done with the Derived Column transformation, except that its expression cannot be a SQL statement and it doesn't need to be evaluated it for every row of X anyway. Which leads me to a similar conclusion as you: that since a variable could be used in the expression, the result of the query should be saved in a variable. But in SSIS Designer, a variable (in this case, scoped to the data flow task) cannot be specified as an SQL statement.

Help! What is the best practice in this situation?

|||

Kevin,

Your request is basically to be able to do an OUTER JOIN. Is that correct?

I have lamented the lack of an OUTER JOIN component in the past and have requested one for future versions. Unfortunately I did that during beta and that request hasn't made it through to Microsoft Connect. Can I suggest that you go to Microsoft Connect and put in a request for it and then put a link to it up here so that I can vote for it.

If you dont ask then you won't get!

The only way to accomplish what you need in ths instance is to use a script component.

-Jamie

|||

Hello all

There are two ways I could find to tackle this problem.

1) This is very slow and consumes a lot of memory

create a dummy derived column in both tables you want to join and insert a dummy 1(you may need to sort on this column which is the real performance killer). Then use merge join on this field so resulting new table contains the new column coming from the other rowset.

2) Split the DataFlow task into several pieces. Populate a variable (I am assuming the value you want to add as the new column will come from a rowset of count 1) with the first pass. Then use a derived column to insert the new value using this variable.

I am not sure if these are the recommended ways to do it but they worked for me.

Batu

sql

Tuesday, March 20, 2012

Add/Remove Column/Row Groups dynamically in Reporting Services

Hi
Presently I'm working with OLAP and Reporting Services. In which users
are allowed to drag and drop the dimensions and the measures from the
list available for the cube , On droping of the dimension/measure on
Row/Column. I need to generate the matrix. Is it possible in RS, If it
menas, give me idea on this else notes for how to proceed with this.
Regards
Santhimurthy DessingouIf you're using SQL Server 2005, you could probably do this with the new
Report Builder tool, you just need to create a Report Model with all the
dimensions and measures you need.
Alternatively, try searching for a thread called "RS/MDX - Column Parameter
/ Field name in dataset problem"
Or if you use Google groups, you find it at
http://groups.google.no/group/microsoft.public.sqlserver.reportingsvcs/browse_thread/thread/642b5c0d703335b6/568564e89b6bc038?lnk=st&q=Re%3A+RS%2FMDX+-+Column+Parameter+%2F+Field+name+in+dataset+problem&rnum=1&hl=no#568564e89b6bc038
It's a suggestion on how to create a dynamic report. It's limited by a given
number of columns, but it might be possible to elaborate on the ideas to get
what you want.
Kaisa M. Lindahl Lervik
<santhimurthyd@.gmail.com> wrote in message
news:1140600388.351554.135920@.g44g2000cwa.googlegroups.com...
> Hi
> Presently I'm working with OLAP and Reporting Services. In which users
> are allowed to drag and drop the dimensions and the measures from the
> list available for the cube , On droping of the dimension/measure on
> Row/Column. I need to generate the matrix. Is it possible in RS, If it
> menas, give me idea on this else notes for how to proceed with this.
> Regards
> Santhimurthy Dessingou
>

Monday, March 19, 2012

add total row to file via script component

Hi, I have a flat file source going into a script component which manipulates some values and puts those values in a flat file destination. What I now need to do is total a column within the script component and add that value as a row to the destination. At the moment data from source looks something like

ABC, 3

DEF, 5

FGH, 6

I have a variable in script component holding the running total I now want to add that to destination as a row e.g.

ABC, 3

DEF, 5

FGH, 6

Total, 14

This is probably very easy but I don't now how to add the Total row via the component. At the moment all rows are manipulated in the ProcessInputRow sub of component and output column values are assigned here. How do I add the Total row as I need to do this once last input row is complete.

Thanks

You'll need to use an asynchronous output to accomplish this. You could add an async output in addition to the synchronous output you get by default, and just write the running total to it.

See this topic in Books Online:

"Creating an Asynchronous Transformation with the Script Component"

|||You could also just use a multicast and an Aggregate transform to accomplish the same thing.|||Great thanks, Asynchronous Transformation worked

add total row to file via script component

Hi, I have a flat file source going into a script component which manipulates some values and puts those values in a flat file destination. What I now need to do is total a column within the script component and add that value as a row to the destination. At the moment data from source looks something like

ABC, 3

DEF, 5

FGH, 6

I have a variable in script component holding the running total I now want to add that to destination as a row e.g.

ABC, 3

DEF, 5

FGH, 6

Total, 14

This is probably very easy but I don't now how to add the Total row via the component. At the moment all rows are manipulated in the ProcessInputRow sub of component and output column values are assigned here. How do I add the Total row as I need to do this once last input row is complete.

Thanks

You'll need to use an asynchronous output to accomplish this. You could add an async output in addition to the synchronous output you get by default, and just write the running total to it.

See this topic in Books Online:

"Creating an Asynchronous Transformation with the Script Component"

|||You could also just use a multicast and an Aggregate transform to accomplish the same thing.|||Great thanks, Asynchronous Transformation worked

Sunday, March 11, 2012

Add space between matrix row group

I have a 2 row groups in a matrix and I need to add some space between the top one so that all the columns don't run together. Is there a way to do this?

Click on the row that you want to add the space below, go to the properties window and increase your 'Height' value. Also, make sure that the 'VerticalAlign' field is set to 'Top'. This will add empty space between that row and the one directly below it.

Hope this helps.

Jarret

|||I guess I wasn't clear. I dont need space between the rows, but between the last column in a row group and the first column in the next row group. Does that make sense?|||

Click on the last column in the matrix, and in the properties window, increase the Padding-Right value. You might want to increase the Width of that column to handle the additional padding. Does this do what you are trying to accomplish?

Hope this helps.

Jarret

|||

No, padding won't help. Here's my layout. I need more space between the subject areas.

ELA

Math

Science

Social Studies

Below Basic

Basic

Proficient

Advanced

Below Basic

Basic

Proficient

Advanced

Below Basic

Basic

Proficient

Advanced

Below Basic

Basic

Proficient

Advanced

17%

46%

37%

1%

14%

36%

30%

20%

20%

32%

23%

24%

40%

37%

9%

15%

9%

57%

30%

4%

22%

49%

16%

13%

22%

50%

13%

15%

14%

44%

22%

21%

16%

36%

44%

4%

13%

39%

22%

26%

27%

33%

21%

18%

23%

40%

17%

20%

|||That's what it currently looks like. How do you want it to look?|||

So, you are wanting something like a 'spacer' column? What if you add another blank column to you report? Right click your textbox below the 'Advanced' column and select 'Add Column', then just leave it blank.

Jarret

|||

ELAMath
Below BasicBasicProficientAdvancedBelow BasicBasicProficientAdvanced
17%46%37%1%14%36%30%20%
9%57%30%4%22%49%16%13%
16%36%44%4%13%39%22%26%

See the space I've added between ELA and Math sections? Thats what I want.

|||That adds a second column of data that will repeat. So instead of one column under advanced I have two.|||Would you still want the tables to appear horizontally next to each other? Have you considered placing the matrix in a list control and adding a groupping by subject? This would effectively give you a matrix per subject but they would be layed out vertically.|||I have to lay them out horizontally bc of how many rows there are. If I do it vertically the report gets too long to read.|||Does anybody have a clue how to do this? It seems like it'd be so simple...

Thursday, March 8, 2012

Add nunmeration to table

Hello.
Whats the easiest way to add a column with a numeration to my table?
I want the users to have an easier life finding on which row they are
talking.
I preffer of course doing it in reporting service and not adding a
column in my dataset.
Thanks.Add the following to a grid cell or control in the detail section of your
report:
=RunningValue(1,Sum,Nothing)
This will count each row. If you only want to count each row across a
specific group, then change the Nothing to "MyGroup"
Michael
"nicknack" wrote:
> Hello.
> Whats the easiest way to add a column with a numeration to my table?
> I want the users to have an easier life finding on which row they are
> talking.
> I preffer of course doing it in reporting service and not adding a
> column in my dataset.
> Thanks.
>

Add numeration to table

Hello.
Whats the easiest way to add a column with a numeration to my table?
I want the users to have an easier life finding on which row they are
talking.
I preffer of course doing it in reporting service and not adding a
column in my dataset.
Thanks.add a text box with an expression displaying the rownumber from the Common
Functions, Miscellaneous grouping
"nicknack" <roezohar@.gmail.com> wrote in message
news:1184757863.411660.8190@.m37g2000prh.googlegroups.com...
> Hello.
> Whats the easiest way to add a column with a numeration to my table?
> I want the users to have an easier life finding on which row they are
> talking.
> I preffer of course doing it in reporting service and not adding a
> column in my dataset.
> Thanks.
>

Add numeration to a table


Hello.

Whats the easiest way to add a column with a numeration to my table?

I want the users to have an easier life finding on which row they are talking.

I preffer of course doing it in reporting service and not adding a column in my dataset.

Thanks.

I found it:

RowNumber(Scope)

Thanks

add new row to existing table

I have about 600 records that I want to add to an existing table in a DB. T
he table row contains about 48 columns. I have data for 4 of those columns
in an excel spreadsheet. All other columns except 3 can be null. If I put
a value in the non-null col
umns, then I assume I can use the DTS import wizard to import the data from
the spread sheet to the desired table in the DB. Am I correct?
Thanks
JoelJoel,
You should be able to do that. You can also try something like this:
insert into
yourTable(a,b,c,d,other_not_nullA,other_
not_nullB,other_not_nullC)
select A,B,C,D,'whatever', 'whatever', 'whatever'
from OpenRowset(
'Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;
HDR=YES;
IMEX=1;
Database=c:\path_to\yourSpreadsheet.xls',
'select * from [Sheet1$]'
)
If the other not null columns are not strings, use constants of the
appropriate type. The DTS wizard might be easier - there are some
issues importing Excel with OpenRowset if the column types aren't
obvious from the data, and with blank values, but with only 600 rows,
you can probably just run the select from the insert above and look to
see if what you see is right.
A quick and dirty way to get data from Excel to SQL Server is to use
string functions and concatenation in Excel to create a column something
like
="insert into
yourTable(a,b,c,d,other_not_nullA,other_
not_nullB,other_not_nullC)
values('"&A1&"','"&A2 ... and so on,
then copy and paste the insert statements into Query Analyzer and run them.
Steve Kass
Drew University
joel wrote:

>I have about 600 records that I want to add to an existing table in a DB. The tabl
e row contains about 48 columns. I have data for 4 of those columns in an excel spr
eadsheet. All other columns except 3 can be null. If I put a value in the non-null
co
lumns, then I assume I can use the DTS import wizard to import the data from the spread she
et to the desired table in the DB. Am I correct?
>Thanks
>Joel
>

Add New Row Problems

This code runs with no errors.
The problem is nothing actually gets updated.

Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim mEmp As New YessClass1
Dim EmpID As Long
Dim Conn As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))

'Dim mRdg As YessClass1 = New YessClass1
Dim lngID As Long
'This is to save a record to tblFeedback
Dim strSelect As String = "SELECT * FROM tblFeedback"
'now create the data adapter object and connect it to
'sql string and the connection
Dim dscmd As New SqlDataAdapter(strSelect, Conn)
' Load a data set.
ds = New DataSet
'data Adapter fill with dataset, name of dataset
dscmd.Fill(ds, "Feedback")
SqlConnection1.Close()
'get the EmployeeID and the Rounding RecordID
Try
mEmp = CType(Session("objEmp"), YessClass1)
EmpID = mEmp.Employee
Try
Dim dt As DataTable = ds.Tables.Item("FeedBack")
Dim rowFeedback As DataRow = dt.NewRow

With rowFeedback
.Item("RoundingID") = RdgID
.Item("QuestionID") = Me.lstQuestion.SelectedItem.Value
.Item("ResponseActionID") = Me.lstAction.SelectedItem.Value
.Item("EmployeeID") = Me.lstDirector.SelectedItem.Value
.Item("ActivityID") = Me.lstActivity.SelectedItem.Value
.Item("Feedback") = Me.txtFeedback.Text
If Me.ckReq.Checked = True Then
.Item("Acknowledgement") = 1
.Item("AckDate") = Now
End If
End With

dt.Rows.Add(rowFeedback)

Catch ex As Exception

Response.Write("Error occured" & ex.Message)
End Try
Catch ex As Exception
Response.Write("ERROR: " & ex.Message)
End Try
End SubWhere are you actually updating the database? Adding the row to the DataTable does not do it. You need to call .Update somewhere on the DataSet.

Tuesday, March 6, 2012

add new column with runing numbers

Hello.
Whats the easiest way to add a column with a numeration to my table?
I want the users to have an easier life finding on which row they are
talking.
I preffer of course doing it in reporting service and not adding a
column in my dataset.
Thanks.
(its look like i have problems posting here so I hope it won't be
posted twice)You can simply add another column to your table control in a report and set
its Value property to expression containing RowNumber function. RowNumber
function in RS 2005 can take a string parameter - scope. That allows you to
reset the numeration in case you have some groupings.
--
Regards
Pawel Potasinski
U¿ytkownik "nicknack" <roezohar@.gmail.com> napisa³ w wiadomo?ci
news:1184825034.216931.48630@.x35g2000prf.googlegroups.com...
> Hello.
> Whats the easiest way to add a column with a numeration to my table?
> I want the users to have an easier life finding on which row they are
> talking.
> I preffer of course doing it in reporting service and not adding a
> column in my dataset.
> Thanks.
> (its look like i have problems posting here so I hope it won't be
> posted twice)
>|||Hi Pawel ,
Thanks for the replay.
I found the answer in one of my RS books :)
Never thought I'm going to open them.
Thank!
On 19 , 08:34, "Pawel Potasinski" <pawel.potasin...@.gmail.com>
wrote:
> You can simply add another column to your table control in a report and s=et
> its Value property to expression containing RowNumber function. RowNumber
> function in RS 2005 can take a string parameter - scope. That allows you =to
> reset the numeration in case you have some groupings.
> --
> Regards
> Pawel Potasinski
> U=BFytkownik "nicknack" <roezo...@.gmail.com> napisa=B3 w wiadomo=9Ccinews=:1184825034.216931.48630@.x35g2000prf.googlegroups.com...
> > Hello.
> > Whats the easiest way to add a column with a numeration to my table?
> > I want the users to have an easier life finding on which row they are
> > talking.
> > I preffer of course doing it in reporting service and not adding a
> > column in my dataset.
> > Thanks.
> > (its look like i have problems posting here so I hope it won't be
> > posted twice)|||I know what you mean. Lots of fine books, no time to read them...
--
Regards
Pawel Potasinski
Uzytkownik "nicknack" <roezohar@.gmail.com> napisal w wiadomosci
news:1185102275.499795.287050@.w3g2000hsg.googlegroups.com...
Hi Pawel ,
Thanks for the replay.
I found the answer in one of my RS books :)
Never thought I'm going to open them.
Thank!
On 19 , 08:34, "Pawel Potasinski" <pawel.potasin...@.gmail.com>
wrote:
> You can simply add another column to your table control in a report and
> set
> its Value property to expression containing RowNumber function. RowNumber
> function in RS 2005 can take a string parameter - scope. That allows you
> to
> reset the numeration in case you have some groupings.
> --
> Regards
> Pawel Potasinski
> U¿ytkownik "nicknack" <roezo...@.gmail.com> napisa³ w
> wiadomoocinews:1184825034.216931.48630@.x35g2000prf.googlegroups.com...
> > Hello.
> > Whats the easiest way to add a column with a numeration to my table?
> > I want the users to have an easier life finding on which row they are
> > talking.
> > I preffer of course doing it in reporting service and not adding a
> > column in my dataset.
> > Thanks.
> > (its look like i have problems posting here so I hope it won't be
> > posted twice)

Friday, February 24, 2012

Add Column Values To the Bottom Of the Row By Condition

Hi
I am getting some results from stored procedure.
Name Value1 Value2 Value3 Total
North 1 2 3 6
North 4 5 6 15
South 5 6 7 18
Footer (North) 5 7 9 21
Footer(South) 5 6 7 18
I displaying footer for each group and i want to display Total value of
the column for that respective group Name.Is therea way to add all
column value depending up on the condition.
For North add only 2 rows.
Can any one help on this issue.
Thankstry sum in the group
=Sum(field!abc.value, "group1") you can have scope in the sum.
Amarnath
"vamsi" wrote:
> Hi
> I am getting some results from stored procedure.
> Name Value1 Value2 Value3 Total
> North 1 2 3 6
> North 4 5 6 15
> South 5 6 7 18
> Footer (North) 5 7 9 21
> Footer(South) 5 6 7 18
>
> I displaying footer for each group and i want to display Total value of
> the column for that respective group Name.Is therea way to add all
> column value depending up on the condition.
> For North add only 2 rows.
> Can any one help on this issue.
> Thanks
>

Sunday, February 19, 2012

add border in matrix report with 2 row group

I have matrix report with 2 row group.

I want to add border to the first Row group.

when I Try add border in the layout tab. the border added to all the cell.

here is my image to show:
http://img2.tapuz.co.il/forums/1_92118232.jpg

is it possible?

thanks!try again

Sunday, February 12, 2012

Ad Hoc Company Security

Is there a way in Ad Hoc reports to prevent users from querying data from another companies data? In my database each table row has a company Id so that my application only displays data for the currently logged in users company. Can I inforce this in ad hoc reporting?

Thanks,

Duncan

You could create a view that displays only the data for the company of the current user and then grant permission only to that view.

|||

The only problem with that is that you would need to create a different view for every company and have to set up a different model for each company. We have decided to leave out Ad-Hoc reporting for this version of our application and look at other alternatives later.

Duncan

Thursday, February 9, 2012

Actual vs. Estimated Row Counts

I have a stored procedure that contains a complex query of approximately 16
joins, (a mixture of inner and left joins). These joins are mostly on
standard user tables, but includes joins on two temporary tables and two non-
indexable views.
I have rewritten the query so as to reduce the reads from 5 million plus, to
about 1.6 million reads using some dynamic sql and adding additional indexes.
Still, in the execution plan, several of the user tables have estimated vs.
actual row counts that are quite different, such as 1 Estimated row versus
135,000 actual rows. These tables are using, what I consider the appropriate
index, but, as stated, the actual vs. estimated are way off.
The procedure takes several arguments and I set those arguments as local
variables in the procedure to prevent parameter sniffing.
I was hoping to get a better plan by getting the actual versus estimated row
counts closer. I have ran "update statistics <table_name> with fullscan" on
all the major tables used in the query and especially on those tables whose
actual vs. estimated are way off. This had no effect on the actual vs.
estimated row counts. I have also run sp_updatestats, dbcc dbreindex on the
tables, sp_recompile, but in each case, the estimated vs. actual is still way
off.
I have considered reordering some of the inner and left joins, but was not
sure if that would have any affect.
Would you be able to advise on what else one might do to get the actual vs.
estimated more in line?
Message posted via droptable.com
http://www.droptable.com/Uwe/Forums...erver/200610/1
its difficult to get a better and more accurate plan after your actions
(updating stats etc...)
Specially with left joins...
the only way is to force the way you want to do your joins (manually
specify the hash/ merge option in the joins, setup the better order for your
joins etc...)
in this case you force SQL Server to use your hints instead of using its own
generated plan.
"cbrichards via droptable.com" <u3288@.uwe> wrote in message
news:679360284efd2@.uwe...
>I have a stored procedure that contains a complex query of approximately 16
> joins, (a mixture of inner and left joins). These joins are mostly on
> standard user tables, but includes joins on two temporary tables and two
> non-
> indexable views.
> I have rewritten the query so as to reduce the reads from 5 million plus,
> to
> about 1.6 million reads using some dynamic sql and adding additional
> indexes.
> Still, in the execution plan, several of the user tables have estimated
> vs.
> actual row counts that are quite different, such as 1 Estimated row versus
> 135,000 actual rows. These tables are using, what I consider the
> appropriate
> index, but, as stated, the actual vs. estimated are way off.
> The procedure takes several arguments and I set those arguments as local
> variables in the procedure to prevent parameter sniffing.
> I was hoping to get a better plan by getting the actual versus estimated
> row
> counts closer. I have ran "update statistics <table_name> with fullscan"
> on
> all the major tables used in the query and especially on those tables
> whose
> actual vs. estimated are way off. This had no effect on the actual vs.
> estimated row counts. I have also run sp_updatestats, dbcc dbreindex on
> the
> tables, sp_recompile, but in each case, the estimated vs. actual is still
> way
> off.
> I have considered reordering some of the inner and left joins, but was not
> sure if that would have any affect.
> Would you be able to advise on what else one might do to get the actual
> vs.
> estimated more in line?
> --
> Message posted via droptable.com
> http://www.droptable.com/Uwe/Forums...erver/200610/1
>
|||> The procedure takes several arguments and I set those arguments as local
> variables in the procedure to prevent parameter sniffing.
That way, the optimizer uses hard-coded values to determine selectivity. Something like:
= 10% (actually, it might go by density in the statistics, if available)
> 30%
BETWEEN 25%
The percentage for the values differs from release to release, and can change even between service
packs. So, in other words, a variable is *not* the same thing as the optimizer knowing the value you
are looking for.
For the optimizer to *know* the value and have a static plan, you have to rely on parameter
sniffing. This value in the plan might of course be off for the subsequent usages of the plan.
Or, you would have to get a new plan for each execution. Either break out the critical parts of the
procedure to its own procedures and create them WITH RECOMPILE, or in 2005 you can add RECOMPILE
hint at the query level. Or you can in 2005 even say OPTIMIZE FOR a certain value.
You can of course add WITH RECOMPILE for the whole procedure, but then none of the DML statements in
the procedure will be pre-optimized.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"cbrichards via droptable.com" <u3288@.uwe> wrote in message news:679360284efd2@.uwe...
>I have a stored procedure that contains a complex query of approximately 16
> joins, (a mixture of inner and left joins). These joins are mostly on
> standard user tables, but includes joins on two temporary tables and two non-
> indexable views.
> I have rewritten the query so as to reduce the reads from 5 million plus, to
> about 1.6 million reads using some dynamic sql and adding additional indexes.
> Still, in the execution plan, several of the user tables have estimated vs.
> actual row counts that are quite different, such as 1 Estimated row versus
> 135,000 actual rows. These tables are using, what I consider the appropriate
> index, but, as stated, the actual vs. estimated are way off.
> The procedure takes several arguments and I set those arguments as local
> variables in the procedure to prevent parameter sniffing.
> I was hoping to get a better plan by getting the actual versus estimated row
> counts closer. I have ran "update statistics <table_name> with fullscan" on
> all the major tables used in the query and especially on those tables whose
> actual vs. estimated are way off. This had no effect on the actual vs.
> estimated row counts. I have also run sp_updatestats, dbcc dbreindex on the
> tables, sp_recompile, but in each case, the estimated vs. actual is still way
> off.
> I have considered reordering some of the inner and left joins, but was not
> sure if that would have any affect.
> Would you be able to advise on what else one might do to get the actual vs.
> estimated more in line?
> --
> Message posted via droptable.com
> http://www.droptable.com/Uwe/Forums...erver/200610/1
>
|||Thanks for your reply Jeje.
In regards to your comment of setting up a better order on my joins, is the
guide to setting up joins...ordering joins with the most selective join
first, followed by the next most selective join, etc., etc.?
Jeje wrote:[vbcol=seagreen]
>its difficult to get a better and more accurate plan after your actions
>(updating stats etc...)
>Specially with left joins...
>the only way is to force the way you want to do your joins (manually
>specify the hash/ merge option in the joins, setup the better order for your
>joins etc...)
>in this case you force SQL Server to use your hints instead of using its own
>generated plan.
>[quoted text clipped - 36 lines]
Message posted via droptable.com
http://www.droptable.com/Uwe/Forums...erver/200610/1

Actual vs. Estimated Row Counts

I have a stored procedure that contains a complex query of approximately 16
joins, (a mixture of inner and left joins). These joins are mostly on
standard user tables, but includes joins on two temporary tables and two non
-
indexable views.
I have rewritten the query so as to reduce the reads from 5 million plus, to
about 1.6 million reads using some dynamic sql and adding additional indexes
.
Still, in the execution plan, several of the user tables have estimated vs.
actual row counts that are quite different, such as 1 Estimated row versus
135,000 actual rows. These tables are using, what I consider the appropriate
index, but, as stated, the actual vs. estimated are way off.
The procedure takes several arguments and I set those arguments as local
variables in the procedure to prevent parameter sniffing.
I was hoping to get a better plan by getting the actual versus estimated row
counts closer. I have ran "update statistics <table_name> with fullscan" on
all the major tables used in the query and especially on those tables whose
actual vs. estimated are way off. This had no effect on the actual vs.
estimated row counts. I have also run sp_updatestats, dbcc dbreindex on the
tables, sp_recompile, but in each case, the estimated vs. actual is still wa
y
off.
I have considered reordering some of the inner and left joins, but was not
sure if that would have any affect.
Would you be able to advise on what else one might do to get the actual vs.
estimated more in line?
Message posted via droptable.com
http://www.droptable.com/Uwe/Forum...server/200610/1its difficult to get a better and more accurate plan after your actions
(updating stats etc...)
Specially with left joins...
the only way is to force the way you want to do your joins (manually
specify the hash/ merge option in the joins, setup the better order for your
joins etc...)
in this case you force SQL Server to use your hints instead of using its own
generated plan.
"cbrichards via droptable.com" <u3288@.uwe> wrote in message
news:679360284efd2@.uwe...
>I have a stored procedure that contains a complex query of approximately 16
> joins, (a mixture of inner and left joins). These joins are mostly on
> standard user tables, but includes joins on two temporary tables and two
> non-
> indexable views.
> I have rewritten the query so as to reduce the reads from 5 million plus,
> to
> about 1.6 million reads using some dynamic sql and adding additional
> indexes.
> Still, in the execution plan, several of the user tables have estimated
> vs.
> actual row counts that are quite different, such as 1 Estimated row versus
> 135,000 actual rows. These tables are using, what I consider the
> appropriate
> index, but, as stated, the actual vs. estimated are way off.
> The procedure takes several arguments and I set those arguments as local
> variables in the procedure to prevent parameter sniffing.
> I was hoping to get a better plan by getting the actual versus estimated
> row
> counts closer. I have ran "update statistics <table_name> with fullscan"
> on
> all the major tables used in the query and especially on those tables
> whose
> actual vs. estimated are way off. This had no effect on the actual vs.
> estimated row counts. I have also run sp_updatestats, dbcc dbreindex on
> the
> tables, sp_recompile, but in each case, the estimated vs. actual is still
> way
> off.
> I have considered reordering some of the inner and left joins, but was not
> sure if that would have any affect.
> Would you be able to advise on what else one might do to get the actual
> vs.
> estimated more in line?
> --
> Message posted via droptable.com
> http://www.droptable.com/Uwe/Forum...server/200610/1
>|||> The procedure takes several arguments and I set those arguments as local
> variables in the procedure to prevent parameter sniffing.
That way, the optimizer uses hard-coded values to determine selectivity. Som
ething like:
= 10% (actually, it might go by density in the statistics, if available)
> 30%
BETWEEN 25%
The percentage for the values differs from release to release, and can chang
e even between service
packs. So, in other words, a variable is *not* the same thing as the optimiz
er knowing the value you
are looking for.
For the optimizer to *know* the value and have a static plan, you have to re
ly on parameter
sniffing. This value in the plan might of course be off for the subsequent u
sages of the plan.
Or, you would have to get a new plan for each execution. Either break out th
e critical parts of the
procedure to its own procedures and create them WITH RECOMPILE, or in 2005 y
ou can add RECOMPILE
hint at the query level. Or you can in 2005 even say OPTIMIZE FOR a certain
value.
You can of course add WITH RECOMPILE for the whole procedure, but then none
of the DML statements in
the procedure will be pre-optimized.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"cbrichards via droptable.com" <u3288@.uwe> wrote in message news:679360284efd2@.uwe...[vbcol
=seagreen]
>I have a stored procedure that contains a complex query of approximately 16
> joins, (a mixture of inner and left joins). These joins are mostly on
> standard user tables, but includes joins on two temporary tables and two n
on-
> indexable views.
> I have rewritten the query so as to reduce the reads from 5 million plus,
to
> about 1.6 million reads using some dynamic sql and adding additional index
es.
> Still, in the execution plan, several of the user tables have estimated vs
.
> actual row counts that are quite different, such as 1 Estimated row versus
> 135,000 actual rows. These tables are using, what I consider the appropria
te
> index, but, as stated, the actual vs. estimated are way off.
> The procedure takes several arguments and I set those arguments as local
> variables in the procedure to prevent parameter sniffing.
> I was hoping to get a better plan by getting the actual versus estimated r
ow
> counts closer. I have ran "update statistics <table_name> with fullscan" o
n
> all the major tables used in the query and especially on those tables whos
e
> actual vs. estimated are way off. This had no effect on the actual vs.
> estimated row counts. I have also run sp_updatestats, dbcc dbreindex on th
e
> tables, sp_recompile, but in each case, the estimated vs. actual is still
way
> off.
> I have considered reordering some of the inner and left joins, but was not
> sure if that would have any affect.
> Would you be able to advise on what else one might do to get the actual vs
.
> estimated more in line?
> --
> Message posted via droptable.com
> http://www.droptable.com/Uwe/Forum...server/200610/1
>[/vbcol]|||Thanks for your reply Jeje.
In regards to your comment of setting up a better order on my joins, is the
guide to setting up joins...ordering joins with the most selective join
first, followed by the next most selective join, etc., etc.?
Jeje wrote:[vbcol=seagreen]
>its difficult to get a better and more accurate plan after your actions
>(updating stats etc...)
>Specially with left joins...
>the only way is to force the way you want to do your joins (manually
>specify the hash/ merge option in the joins, setup the better order for you
r
>joins etc...)
>in this case you force SQL Server to use your hints instead of using its ow
n
>generated plan.
>
>[quoted text clipped - 36 lines]
Message posted via droptable.com
http://www.droptable.com/Uwe/Forum...server/200610/1

Actual vs. Estimated Row Counts

I have a stored procedure that contains a complex query of approximately 16
joins, (a mixture of inner and left joins). These joins are mostly on
standard user tables, but includes joins on two temporary tables and two non-
indexable views.
I have rewritten the query so as to reduce the reads from 5 million plus, to
about 1.6 million reads using some dynamic sql and adding additional indexes.
Still, in the execution plan, several of the user tables have estimated vs.
actual row counts that are quite different, such as 1 Estimated row versus
135,000 actual rows. These tables are using, what I consider the appropriate
index, but, as stated, the actual vs. estimated are way off.
The procedure takes several arguments and I set those arguments as local
variables in the procedure to prevent parameter sniffing.
I was hoping to get a better plan by getting the actual versus estimated row
counts closer. I have ran "update statistics <table_name> with fullscan" on
all the major tables used in the query and especially on those tables whose
actual vs. estimated are way off. This had no effect on the actual vs.
estimated row counts. I have also run sp_updatestats, dbcc dbreindex on the
tables, sp_recompile, but in each case, the estimated vs. actual is still way
off.
I have considered reordering some of the inner and left joins, but was not
sure if that would have any affect.
Would you be able to advise on what else one might do to get the actual vs.
estimated more in line?
--
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200610/1its difficult to get a better and more accurate plan after your actions
(updating stats etc...)
Specially with left joins...
the only way is to force the way you want to do your joins (manually
specify the hash/ merge option in the joins, setup the better order for your
joins etc...)
in this case you force SQL Server to use your hints instead of using its own
generated plan.
"cbrichards via SQLMonster.com" <u3288@.uwe> wrote in message
news:679360284efd2@.uwe...
>I have a stored procedure that contains a complex query of approximately 16
> joins, (a mixture of inner and left joins). These joins are mostly on
> standard user tables, but includes joins on two temporary tables and two
> non-
> indexable views.
> I have rewritten the query so as to reduce the reads from 5 million plus,
> to
> about 1.6 million reads using some dynamic sql and adding additional
> indexes.
> Still, in the execution plan, several of the user tables have estimated
> vs.
> actual row counts that are quite different, such as 1 Estimated row versus
> 135,000 actual rows. These tables are using, what I consider the
> appropriate
> index, but, as stated, the actual vs. estimated are way off.
> The procedure takes several arguments and I set those arguments as local
> variables in the procedure to prevent parameter sniffing.
> I was hoping to get a better plan by getting the actual versus estimated
> row
> counts closer. I have ran "update statistics <table_name> with fullscan"
> on
> all the major tables used in the query and especially on those tables
> whose
> actual vs. estimated are way off. This had no effect on the actual vs.
> estimated row counts. I have also run sp_updatestats, dbcc dbreindex on
> the
> tables, sp_recompile, but in each case, the estimated vs. actual is still
> way
> off.
> I have considered reordering some of the inner and left joins, but was not
> sure if that would have any affect.
> Would you be able to advise on what else one might do to get the actual
> vs.
> estimated more in line?
> --
> Message posted via SQLMonster.com
> http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200610/1
>|||> The procedure takes several arguments and I set those arguments as local
> variables in the procedure to prevent parameter sniffing.
That way, the optimizer uses hard-coded values to determine selectivity. Something like:
= 10% (actually, it might go by density in the statistics, if available)
> 30%
BETWEEN 25%
The percentage for the values differs from release to release, and can change even between service
packs. So, in other words, a variable is *not* the same thing as the optimizer knowing the value you
are looking for.
For the optimizer to *know* the value and have a static plan, you have to rely on parameter
sniffing. This value in the plan might of course be off for the subsequent usages of the plan.
Or, you would have to get a new plan for each execution. Either break out the critical parts of the
procedure to its own procedures and create them WITH RECOMPILE, or in 2005 you can add RECOMPILE
hint at the query level. Or you can in 2005 even say OPTIMIZE FOR a certain value.
You can of course add WITH RECOMPILE for the whole procedure, but then none of the DML statements in
the procedure will be pre-optimized.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"cbrichards via SQLMonster.com" <u3288@.uwe> wrote in message news:679360284efd2@.uwe...
>I have a stored procedure that contains a complex query of approximately 16
> joins, (a mixture of inner and left joins). These joins are mostly on
> standard user tables, but includes joins on two temporary tables and two non-
> indexable views.
> I have rewritten the query so as to reduce the reads from 5 million plus, to
> about 1.6 million reads using some dynamic sql and adding additional indexes.
> Still, in the execution plan, several of the user tables have estimated vs.
> actual row counts that are quite different, such as 1 Estimated row versus
> 135,000 actual rows. These tables are using, what I consider the appropriate
> index, but, as stated, the actual vs. estimated are way off.
> The procedure takes several arguments and I set those arguments as local
> variables in the procedure to prevent parameter sniffing.
> I was hoping to get a better plan by getting the actual versus estimated row
> counts closer. I have ran "update statistics <table_name> with fullscan" on
> all the major tables used in the query and especially on those tables whose
> actual vs. estimated are way off. This had no effect on the actual vs.
> estimated row counts. I have also run sp_updatestats, dbcc dbreindex on the
> tables, sp_recompile, but in each case, the estimated vs. actual is still way
> off.
> I have considered reordering some of the inner and left joins, but was not
> sure if that would have any affect.
> Would you be able to advise on what else one might do to get the actual vs.
> estimated more in line?
> --
> Message posted via SQLMonster.com
> http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200610/1
>|||Thanks for your reply Jeje.
In regards to your comment of setting up a better order on my joins, is the
guide to setting up joins...ordering joins with the most selective join
first, followed by the next most selective join, etc., etc.?
Jeje wrote:
>its difficult to get a better and more accurate plan after your actions
>(updating stats etc...)
>Specially with left joins...
>the only way is to force the way you want to do your joins (manually
>specify the hash/ merge option in the joins, setup the better order for your
>joins etc...)
>in this case you force SQL Server to use your hints instead of using its own
>generated plan.
>>I have a stored procedure that contains a complex query of approximately 16
>> joins, (a mixture of inner and left joins). These joins are mostly on
>[quoted text clipped - 36 lines]
>> vs.
>> estimated more in line?
--
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200610/1