Construct Variable Name?

Mar 16, 2006

Can you contruct a variable name from another variable? For example, I want the following to PRINT 10


DECLARE @var1 INT
DECLARE @var2 INT

SET @var1 = 10
SET @var2 = 20

PRINT '@var' + '1'


This prints the variable name, not the contents of the var. I tried to parse it with square brackets, but no luck.

Thanks,
Carl

View 6 Replies


ADVERTISEMENT

SQL Construct

Dec 19, 2006

Hi all,

I had a question regarding SQL construct.

I had a table named "info" and I would like to show Lot_Id as distinct. Besides that , I would also like to show wafer_id and wafer_starttime. May I know how to construct this using select statement?

Thanks

View 1 Replies View Related

Can Someone Help Me Construct A SQL Command....

Oct 18, 2005

My head hurts...it might be an easy one for many people, but cant seem to figure a way to do it.Ok, I have a table with a field called Ad_Price.  This field is a nvarchar one, theres many different value in it, all of them corresponding to a price.  Now, what I want to do is only get the row that are not written in a good price format (like123$  is wrong, but 123.00 is good, but only value following this exemple)For exemple, if I have all these value145.876785.34654$45 to negociate1bvcaa0.01876.556the value I want to have are:654$45 to negociate1bvcaa876.556because they dont follow the format I wantso im not sure if my explication was clear enough..all in all what I want to complete is the WHERE part of my SQL instruction...what should I put in:SELECT *FROM AdsWHERE ???????thansk for taking the time to read this

View 2 Replies View Related

CASE SQL Construct

Sep 27, 2005

I am using the following code to construct an SQL 7.0 View Column

"CASE WHEN [DailyHours] > SUM([TransAmt]) THEN 0 ELSE 1 END"

and it works great!!

However, when I try the same line in SQL 2000, I get the message "The query designer does not support the case SQL construct"

The help screen is no help as all it says is "the syntax you entered is valid but is not supported visually by Query Designer. Be sure the verify your syntax before saving."

It will not let me save, so I'm not sure what to do from here now????

View 8 Replies View Related

Construct A SelectCommand From Three VB Variables In ASP.NET 2.0

Jun 18, 2008

Dear Group,
I'm upgrading a "classic" ASP app to ASP.NET 2.0.  The database is stored on a SQL Server box in-house.  I'm looking to inject a bit of flexibility into the SQLDataSource SelectCommand property.
What I mean is this: depending on a selection a user makes in the form, I'd like to present a GridView object that displays data filtered by the user's selection.
So I took the original long query string from ASP and broke it in two pieces.  The first piece contains the bulk of the query and it ends just after the WHERE clause.  The second piece is the ORDER BY clause.  I'd like to have the ability to inject an additional term at the end of the WHERE clause (using AND).  That would be the filter.
For example,SELECT LastName, FirstName, InOut, TimeEntered, PhoneExt
FROM TimeClock
WHERE TimeEntered > '6/17/2008'
AND EmploymentState > ''
ORDER BY LastName, FirstName
So, in between the "AND State > '' " and the ORDER BY clause I'd like to insert something like this:AND Department = 'Production'
I'd like the SelectCommand of the SQLDataSource to look like this:SelectCommand="<%= (sql1 & " AND Department = 'Production' " & sql2) %>"
sql1 and sql2 are defined in a <script runat="server"></script> block in the page <head>. The following errors occur even if I have a single variable containing the whole SQL query string (i.e., SelectCommand="<%= sql1 %>").
When I try to run the page I get this error:Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near '<'.
If I remove the quotation marks from around the SelectCommand statement I get:Parser Error Message: Server tags cannot contain <% ... %> constructs.
What's funny about this is that the ConnectionString property of the SQLDataSource looks like this:ConnectionString="<%$ ConnectionStrings:PersonnelDatabaseConnectionString %>"
No complaints from the compiler about the ConnectionString.
Any ideas? Am I simply going to be unable to construct a SelectCommand on-the-fly?

View 9 Replies View Related

How To Construct SQL SELECT Statement

Dec 31, 2003

I want to search an entire table for a particular keyword but i'm not sure how, if the keyword was TEST then I want to return rows where any of the fields contain TEST, THIS IS A TEST, PLEASE TEST THIS etc etc i.e. the keyword can be anywhere in the fields value

I believe I need to use the LIKE clause but i'm not sure how.

Thanks

Ben

View 4 Replies View Related

SQL Construct For Filtering Data

Nov 15, 2005

Hi,I have three dropdown lists branch, month & year. Based on these I need to retrieve data in my Datagrid.I have written the following SQL statement & code in my Refreshgrid():       SqlCmd.CommandText  = " SELECT * "       SqlCmd.CommandText += " FROM HSECData"       SqlCmd.CommandText += " where branchno=" &Branchno       SqlCmd.CommandText += " And yearno=" &YearNo       SqlCmd.CommandText += " And monthno=" &monthNoThis is working fine, initially the datagrid is empty and then displays data when I select say, branch- Melbourne, Year-2005, Month-October  and other exisiting combinations.The problem I am stuck at is when the page loads, initially I want all the data to be displayed in datagrid, i.e. for 'All' branches, 'All' years and 'All' months and then when I select combinations of these dropwdown lists as above the data should be filtered and displayed in those selected combinations. but as of now I get and empty datagrid when I select 'All' from these 3 drop down lists or when the page opens the first time.Can someone kindly guide me with the correct SQL cinstruct to achieve both the requirements?Thanks,Aartee.P.S. I am sorry if I have posted this question in a wrong category in the forum, I was unsure whether I should post it in Datagrid category or SQL server category, I thought this was my best bet.My aplogies.

View 1 Replies View Related

The NOT SQL Construct Or Statement Is Not Supported.

Sep 19, 2007

I need to transmit data from a ##table to an .xls file. The data is exported only for the first time. However, after a while the table will be dropped by SQL Server 2005 automatically.


I'm using Execute SQL Task to check for the existence of an ##Table. And, if does not exists the ##table should be created or something like the example below.

Ex:
IF NOT EXISTS (
SELECT *
FROM ##StateProvince
)

SELECT * INTO ##StateProvince
FROM Person.StateProvince
GO


To keep the session of the ## Table active, but the following error is thrown :

The NOT SQL construct or statement is not supported.

View 4 Replies View Related

How To Construct Table With Unique PK

Oct 31, 2006

Let say I have 6 tables. I want to autogenerate the PK for each table and that is unique for each table and cant be duplicated on other tables. Let say I have table with PK of 1, so table2 to table6 wouldnt have a PK of 1. If table2 have a PK of 2, table1, table3 to table6 wouldnt have a PK of 2. Same for others. Identity will not be appropriate. Will 'uniqueidentifier' data type suffice? How bout guid? Or what must be my datatype? Or what will I do to implement this? Any links? Thanks

View 8 Replies View Related

Best Way To Construct Dynamic Queries

Apr 17, 2008

I am working with a form that I wish to construct a dynamic query from the results of. The forum has a date range and two radio buttons. Each radio button enables a list of items that can be clicked. So for example, if we assume the question,

"What is your favorite food, and what toppings do you like on it?" where the radio buttons are foods, the list boxes are toppings. Assuming the user can choose a Hamburger or a Salad with generic toppings, their choices are as such:

They can choose a Hamburger, with every topping
They can choose a Hamburger with a single topping.
They can choose a Hamburger with multiple toppings.
They can choose a Salad with the same combinations as above.
They cannot choose both a Hamburger and a Salad - mutually exclusive items.

Then, I wish to construct a query that, based on the conditions above, retrieves information relavent to their criteria, such a the number of food items to choose from, their price, etc. - basic information. What is the most efficient way to do this? Should I write a stored procedure with numerous conditionals and all available parameters, constructing the sproc as such:





Code Snippet

CREATE PROCEDURE GetFoodInfo
@from datetime,
@to datetime,
@FoodType varchar(20),

@toppings varchar(20)

AS

BEGIN
DECLARE @query varchar(300)
SET @query = 'SELECT COUNT(DISTINCT ' + @FoodType + ') '


IF @FoodType = 'Hamburger'
SET @query = @query + 'FROM Hamburgers '

ELSE
SET @query = @query + 'FROM Salads '

IF @toppings <> 'ALL'

SET @query = @query ' WHERE Toppings = ' + @toppings



EXEC (@query)

Apologies of this syntax is incorrect, but you get the general idea. Of course, this is a small example - in reality, I would have 5-10 conditional requirements Or, should I generate a stored procedure (or simple query) for each operation? For example, assuming each is a stored procedure:

GetHamburgers <-- would get Hamburgers with all toppings
GetHamburgersWithToppings
GetSalads
GetSaladsWithToppings

What is the best method for what I wish to achieve? What is fastest? Is there a better way than I have listed? Thank you.

Again, this is a small example, but I hope someone can help.

View 3 Replies View Related

The OVER SQL Construct Or Statement Is Not Supported.

Jun 14, 2007



Hi there,



I'm trying to run following script in sql command mode in OLE DB Source and it giving me "The OVER SQL construct or statement is not supported." error msg.






Code Snippet

Drop

Table #Tmp_EXT_AATransactions

Select row_number() over (partition by A3.jrnentry,A32.aaGLDistID order by A32.aaGLDistID,A33.aaTrxDimID ) as rownum,

A33.aaTrxDimID,

A33.aaTrxCodeID,

A3.jrnentry,

A32.aaGLDistID,

G2.TRXDATE,

A3.GLPOSTDT,

A3.aaTRXType,

A31.ACTINDX,

A32.DEBITAMT,

A32.CRDTAMNT,

(A32.DEBITAMT - A32.CRDTAMNT) AS Amount

into #Tmp_EXT_AATransactions

From dbo.AAG30000 A3

Inner Join dbo.AAG30001 A31

On A3.aaGLHdrID = A31.aaGLHdrID

Inner Join dbo.AAG30002 A32

On A31.aaGLHdrID = A32.aaGLHdrID

And A31.aaGLDistID = A32.aaGLDistID

Right Outer Join dbo.AAG30003 A33

On A32.aaGLHdrID = A33.aaGLHdrID

And A32.aaGLDistID = A33.aaGLDistID

And A32.aaGLAssignID = A33.aaGLAssignID

Inner Join dbo.GL20000 G2

On A3.jrnentry = G2.jrnentry

And A31.ACTINDX = G2.ACTINDX

And A31.SEQNUMBR = G2.SEQNUMBR

--Where A3.jrnentry in ( '54227','54222','54225')

Select [JrnEntry],

[aaGLDistId],

[TrxDate],

[GLPostDT],

[aaTrxType],

Isnull([1],0) as Dim1,

Isnull([2],0) as Dim2,

Isnull([3],0) as Dim3,

Isnull([4],0) as Dim4,

Isnull([5],0) as Dim5,

Isnull([6],0) as Dim6,

Isnull([7],0) as Dim7,

Isnull([8],0) as Dim8,

Isnull([9],0) as Dim9,

Isnull([10],0) as Dim10,

[ActIndx],

[DEBITAMT],

[CRDTAMNT],

[Amount]

into #Tmp_EXT_AATransactions_Final

From

(

Select [aaTrxDimID],

[aaTrxCodeID],

[aaGLDistID],

[JrnEntry],

[TrxDate],

[GLPostDT],

[aaTrxType],

[ACTINDX],

[DebitAmt],

[CRDTAMNT],

[Amount],

Row_Number() Over (Partition By [aaTrxDimID],[aaGLDistID],[JrnEntry] Order By [aaTrxDimID],[aaGLDistID],[JrnEntry]) RowId

From #Tmp_EXT_AATransactions

) as Data

Pivot

(

Max([aaTrxCodeID]) For [aaTrxDimID] in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10])

) As PVT

Select *

From #Tmp_EXT_AATransactions_Final



I can parse and preview it successfully in OLE DB Source Editor but i can't see any columns in columns mapping. So when i click on Build Query in OLE DB Source Editor i get this error message. Also Its working fine in Management Studio so don't know what's the problem.



Regards,



Vivek

View 3 Replies View Related

How To Programmatically Construct The UpdateCommand For SqlDataSource

Aug 1, 2007

Hi, All
I'm using Gridview and SqlDataSource to dynamically display the contents in different tables, as followed:
<%   dataSource.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["connectionString"];   dataSource.SelectCommand = "SELECT * FROM " + tableName;   gridView.DataBind();
   dataSource.UpdateCommand = "";%>
<asp:SqlDataSource ID="dataSource" runat="server"></asp:SqlDataSource><asp:GridView ID="gridView" runat="server" DataSourceID="dataSource" AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="True" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" PageSize="20" DataKeyNames="ID" OnRowDataBound="tableGridView_RowDataBound">    <HeaderStyle BackColor="#C0C0FF" />    <AlternatingRowStyle BackColor="#C0FFC0" /></asp:GridView>
The datasource take the "tableName" as argument to determine which table to display. My problem is I can't figure out a way to programmatically construct the UpdataCommand for the SqlDataSource. I try to get the field names from the HeaderRow, but all the cells are empty in this row.
Does anyone know what causes the problem or how to construct the UpdateCommand properly. Thanks!

View 3 Replies View Related

How To Construct The Query In Stored Proc

Jun 20, 2005

Hi,In the past I build up the query string within VB.NET page and easy to add the filtering statements in the SQL statement since it is just a string. For example, if user selected an option then include it in the filter, otherwise, just return all rows from table:Codes in ASPX.VB:   Dim SQL as String="SELECT * From Table1"   IF UserOption <> Null then      SQL = SQL & " WHERE Column1=" UserOption"   End ifNow, since I have a complicated page which need to use Stored Procedure to manapulate a temporary table before the final result. But I found when I want to add some user options similar to above, I found I don't know how to do it in Stored Procedure. In the Stored Procedure Property screen, I can't insert a IF..THEN statement within a SELECT statement. Seems I can only check the user option first and then determine the SELECT statement to use. That is: IF UserOption THEN SELECT statement 1 ELSE SELECT statement 2.But it is impossible for me to do this way since I'm not only one user option on the page. User usually can have several filters/selections on his screen. So if check which user option(s) are selected and write a static SELECT statement for it, I will have to program a complicated store procedure to cater all combinations for all user options (where some options may be null).Hope you can understanding what my mean and give me advices.Regards,Raymond

View 8 Replies View Related

HELP On Construct Of Update Stored Proc. .. THANKS!!!

Nov 6, 1998

Referencing the sample stored procedure
below that updates table 'this_table' containing
3 INT columns: 'key', 'col2', 'col3'.

How do I revise the stored procedure so that *** I do not
have to specify ALL the columns *** to update just one column?

e.g. if I want to update @col3 to 9 (exec sp_update_table, @col3 = 9),
how can I set col2 to its existing value?

create proc sp_update_table
@key int,
@col2 int,
@col3 int
as
update this_table
set col2 = @col2,
col3 = @col3
where key = @key
go

View 1 Replies View Related

How To Construct Dynamic Sql In Stored Procedure

Jul 30, 2007

Hi Guys.

I want to construct a SQL in stored procedure in the following way. Please guide me how to achive this



CREATE PROCEDURE P_SAMPLE

(

@P_ONE NVARCHAR(240)

)

AS

BEGIN

DECLARE

@TMP_CNT INT

BEGIN

EXEC ('SELECT @TMP_CNT = 1')

-- PRINT @TMP_CNT

END

END



Regards
Mani


View 2 Replies View Related

The PIVOT SQL Construct Or Statement Is Not Supported.

Oct 25, 2006

I am trying to use a Pivot T-SQL statement in the Table Adapter Configuration Wizard in Visual Studio 2005. I get the error message "The Pivot SQL construct or statement is not supported". Then it executes the SQL statement as if there were no error. Unfortunately, it will not create the table adapter because of the error. Below is the T-SQL statement I am using.



SELECT OrderNumber, OrderDate, custlastname, [1001] AS Dept01, [1002] AS Dept02, [1003] AS Dept03, [1004] AS Dept04, [1005] AS Dept05, [1006] AS Dept06, [1007] AS Dept07, [1008] AS Dept08, [1009] AS Dept09, [1010] AS Dept10, [1011] AS Dept11, [1012] AS Dept12
FROM

(SELECT Orders.Ordernumber, Orders.OrderDate, Customer.custlastname, DeptID, OrderDetail.DetailAmount
FROM OrderDetails od JOIN
Orders ON Orders.OrderNumber = od.OrderNumber JOIN
Customer ON Orders.CustomerID = Customer.CustID
WHERE (DATEPART([Year], OrderDate) = '2006')) p

PIVOT (SUM(OrderDetailAmount) FOR DeptID IN ([1001], [1002], [1003], [1004], [1005], [1006],
[1007], [1008], [1009], [1010], [1011], [1012])) AS pvt
ORDER BY OrderNumber

The statement works fine in Management Studio so I know the syntax is correct.

Any Ideas?

Thanks,

James



View 4 Replies View Related

Import Date Construct Into SQL Database With SSIS

Apr 8, 2008

Hello,

I am currently trying to import following Excel Datasheet into my SQL 2005 Database with SSIS:

Column: Created
For example cells: 18.03.2008 17:47:43

So now I want to get the time, the year, the month and the day seperately out of this column for a later OLAP Analysis.

I created a Data Flow Task, where I imported the Excel source and set the SQL database as target. But now I don't know really how to work with the "Data Conversion" where to extract the dates. In Excel this is just a "customized" cell.

Anyone who can help me in this situation?

Thank you very much.


Greets from Germany,
chle

View 1 Replies View Related

Error:The Query Designer Does Not Support The UNION SQL Construct

Jul 20, 2007

Here is an example of what I am exactly doing!! CREATE VIEW NamesAS SELECT ID, fName, lName FROM Table1 UNION ALL SELECT id, FirstName, LastName FROM TABLE2.  On Executing this...I'm getting the following error.





The Query Designer does not support the UNION SQL construct:    

View 2 Replies View Related

Problem With Analytic Sql Function (The OVER SQL Construct Or Statement Is Not Supported)

Sep 28, 2007

Hi All! 
Could You comment the next situation:I'm configuring my TableAdapter just like Scott Mitchell does in his tutorialhttp://www.asp.net/learn/data-access/tutorial-70-vb.aspxThe only principal difference is that I need Insert/update and deletemethods to be generated (His aim is only SELECT).I'm also using analytic function (ROW_NUMBER) and I'm also gettinwarning “The OVER SQL construct or statement is not supported.â€? Yousay then that it could be ignored. But, in this case statements tomodify data (insert/update and delete) aren't being generated, thoughafter warning SQL command is executed without errors.
So, the question is obvious - why does this warning occur and how mustI perform configuration of TableAdapter based on SQL query withanalytic function?

View 1 Replies View Related

T-SQL (SS2K8) :: Convert Binary String To Table Value Construct?

Mar 21, 2014

Code snippet for changing '00001001001' into a table value construct containing (64,8,1)?

View 6 Replies View Related

Do We Have IF-ELSE Construct Similar To A Flow Chart Execution In SSIS?

Aug 10, 2007



Hi All,
Just needed an insight into the IF-ELSE construct w.r.t its implementation in SSIS or a similar methodology that could be adopted in SSIS while executing a Package.

Scenario : I want to Start with importing data from Different sources to SQL Server Destination. For Which, i define 3 different Data Flow Tasks each involved in importing data from an external source to SQL Server Destination.

1] Text File Inbound Task : Source - Flat File Source ; Destination - SQL Server Dest.
2] Excel Inbound Task : Source - Excel Data Source ; Destination - SQL Server Dest.
3] Xml Inbound Task : Source - XML Data Source ; Destination - SQL Server Dest

Finally i want to execute the package with an IF-ELSE Scenario which will Check for the external Source being :

IF External Source = = Excel file => Execute Excel Inbound Task

ELSE
EXIT

IF External Source = = Text File/Flat File = > Execute Text File Inbound Task
ELSE
EXIT

IF External Source = = Xml File => Execute Xml Inbound Task
ELSE
EXIT


View 1 Replies View Related

Cannot Construct A SELECT DISTINT COUNT... Statement In SSCE 3.1

Oct 4, 2007

Hi everyone,

sorry to b a pest again! Before I made the decision to change the DB used in my app from SQL Server Express to SSCE, I had no problems with constructing a SELECT statement as laid out in the Title.

Basically, I have 2 tables with a one-many relationship between them. In the Parent table, I had a SQL Statement as follows:

SELECT DeptID, DeptName,

(SELECT DISTINCT COUNT(Active) FROM Documents WHERE (Documents.DeptID = Dept.DeptID) AND
(Documents.Active = 'True') AS CountOfActive
FROM Dept


Now in SSCE 3.1, I get an "Unable to parse query" error message when I construct the same SQL statement in my dataset designer.

Any thoughts on how I may solve this?

Much thanx!
Shalan

View 15 Replies View Related

How Do You Construct A Dynamic Stored Procedure With More Than 4000 Chars

Sep 12, 2007

My problem (excuse me for being a novice) is that whenever the query becomes complex
in the @whereclause (and it does) it cant exceed the character limit of a nvarchar. Now if someone could shed some ligfht on this for me I would be
incredibly grateful. I have tried doing the exec(@var1 + @var2) but this did not seem to work.


I have included the stored procedure below.

ALTER PROCEDURE [dbo].[SearchTenderMultiRegions]
(
@whereclause nVarChar(MAX), --4000 chars
@PageIndex int,
@PageSize int
) AS



SET NOCOUNT ON;DECLARE @sql nvarChar(MAX)

SET @sql= 'SELECT * FROM (SELECT DISTINCT TOP (' + CONVERT(nvarchar(10),(@PageIndex*@PageSize))
SET @sql= @sql + ') ROW_NUMBER() OVER (ORDER BY Tenders.ID DESC)AS Row,

Tenders.ID,Tenders.Title,Address.Suburb,Tenders.ClosingDateTime,Tenders.IsApproved,Tenders.TendersSourceID, Tenders.SourceDate,
UserTracking.CreateUserID,UserTracking.CreateDateTime FROM Tenders LEFT JOIN TenderContact ON Tenders.ID = TenderContact.TendersID
LEFT JOIN TenderCategory ON Tenders.ID = TenderCategory.TendersID
LEFT JOIN TenderRegion ON Tenders.ID = TenderRegion.TendersID
LEFT JOIN RegionStateCountry ON TenderRegion.RegionStateCountryID = RegionStateCountry.ID
LEFT JOIN Address ON Tenders.ID = Address.TendersID
LEFT JOIN UserTracking ON Tenders.ID = UserTracking.TendersID
WHERE '

SET @sql= @sql + @whereclause
SET @sql = @sql + ') as TenderSearchEntries
WHERE Row between ('

SET @sql= @sql + CONVERT(nvarchar(10), @PageIndex)
SET @sql= @sql + ' - 1) * '
SET @sql= @sql + CONVERT(nvarchar(10), @PageSize)
SET @sql= @sql + '+ 1 and '
SET @sql= @sql + CONVERT(nvarchar(10), @PageIndex)
SET @sql= @sql + ' * '
SET @sql= @sql + CONVERT(nvarchar(10), @PageSize)

EXEC(@sql)

View 5 Replies View Related

How To Construct The Url Via Database Tables Info To Generate Report

Aug 17, 2007



Please help, i am really really struggling for a logic to handle 100's of reports we have via button click from asp.net webform.
in the button click i am constructing the url :
**************************************************************************************************************
http://localhost/reportserver?/MyReports/StatusReport&UserID=1&ContractID=1&subcode=null
*************************************************************************************************************

I have a table would like to maintain the parameters required for the chosen report:
when the user chooses from list box on the webform for StatusReport, immedeately it fetches the parameters related to Statusreport and gets everything which is stored with a space in between for each parameter, for this report i have 3 parameters:
UserID ContractID subcode

now how can i construct the string based on the above parameters , i am using vb.net as code behind for my webform(asp.net)

please any ideas will help me achieve the logic. please help thank you all very much.


View 4 Replies View Related

SSIS Script Task Alters Package Variable, But Variable Does Not Change.

Oct 25, 2006

I'm working on an SSIS package that uses a vb.net script to grab some XML from a webservice (I'd explain why I'm not using a web service task here, but I'd just get angry), and I wish to then assign the XML string to a package variable which then gets sent along to a DataFlow Task that contains an XML Source that points at said variable. when I copy the XML string into the variable value in the script, if do a quickwatch on the variable (as in Dts.Variable("MyXML").value) it looks as though the new value has been copied to the variable, but when I step out of that task and look at the package explorer the variable is its original value.

I think the problem is that the dataflow XML source has a lock on the variable and so the script task isn't affecting it. Does anyone have any experience with this kind of problem, or know a workaround?

View 1 Replies View Related

Passing A SSIS Global Variable To A Declared Variable In A Query In SQL Task

Mar 6, 2008

I have a SQL Task that updates running totals on a record inserted using a Data Flow Task. The package runs without error, but the actual row does not calculate the running totals. I suspect that the inserted record is not committed until the package completes and the SQL Task is seeing the previous record as the current. Here is the code in the SQL Task:

DECLARE @DV INT;
SET @DV = (SELECT MAX(DateValue) FROM tblTG);
DECLARE @PV INT;
SET @PV = @DV - 1;

I've not been successful in passing a SSIS global variable to a declared parameter, but is it possible to do this:

DECLARE @DV INT;
SET @DV = ?;
DECLARE @PV INT;
SET @PV = @DV - 1;


I have almost 50 references to these parameters in the query so a substitution would be helpful.

Dan

View 4 Replies View Related

SSIS: Problem Mapping Global Variables To Stored Procedure. Can't Pass One Variable To Sp And Return Another Variable From Sp.

Feb 27, 2008

I'm new to SSIS, but have been programming in SQL and ASP.Net for several years. In Visual Studio 2005 Team Edition I've created an SSIS that imports data from a flat file into the database. The original process worked, but did not check the creation date of the import file. I've been asked to add logic that will check that date and verify that it's more recent than a value stored in the database before the import process executes.

Here are the task steps.


[Execute SQL Task] - Run a stored procedure that checks to see if the import is running. If so, stop execution. Otherwise, proceed to the next step.

[Execute SQL Task] - Log an entry to a table indicating that the import has started.

[Script Task] - Get the create date for the current flat file via the reference provided in the file connection manager. Assign that date to a global value (FileCreateDate) and pass it to the next step. This works.

[Execute SQL Task] - Compare this file date with the last file create date in the database. This is where the process breaks. This step depends on 2 variables defined at a global level. The first is FileCreateDate, which gets set in step 3. The second is a global variable named IsNewFile. That variable needs to be set in this step based on what the stored procedure this step calls finds out on the database. Precedence constraints direct behavior to the next proper node according to the TRUE/FALSE setting of IsNewFile.


If IsNewFile is FALSE, direct the process to a step that enters a log entry to a table and conclude execution of the SSIS.

If IsNewFile is TRUE, proceed with the import. There are 5 other subsequent steps that follow this decision, but since those work they are not relevant to this post.
Here is the stored procedure that Step 4 is calling. You can see that I experimented with using and not using the OUTPUT option. I really don't care if it returns the value as an OUTPUT or as a field in a recordset. All I care about is getting that value back from the stored procedure so this node in the decision tree can point the flow in the correct direction.


CREATE PROCEDURE [dbo].[p_CheckImportFileCreateDate]

/*

The SSIS package passes the FileCreateDate parameter to this procedure, which then compares that parameter with the date saved in tbl_ImportFileCreateDate.

If the date is newer (or if there is no date), it updates the field in that table and returns a TRUE IsNewFile bit value in a recordset.

Otherwise it returns a FALSE value in the IsNewFile column.

Example:

exec p_CheckImportFileCreateDate 'GL Account Import', '2/27/2008 9:24 AM', 0

*/

@ProcessName varchar(50)

, @FileCreateDate datetime

, @IsNewFile bit OUTPUT

AS

SET NOCOUNT ON

--DECLARE @IsNewFile bit

DECLARE @CreateDateInTable datetime

SELECT @CreateDateInTable = FileCreateDate FROM tbl_ImportFileCreateDate WHERE ProcessName = @ProcessName

IF EXISTS (SELECT ProcessName FROM tbl_ImportFileCreateDate WHERE ProcessName = @ProcessName)

BEGIN

-- The process exists in tbl_ImportFileCreateDate. Compare the create dates.

IF (@FileCreateDate > @CreateDateInTable)

BEGIN

-- This is a newer file date. Update the table and set @IsNewFile to TRUE.

UPDATE tbl_ImportFileCreateDate

SET FileCreateDate = @FileCreateDate

WHERE ProcessName = @ProcessName

SET @IsNewFile = 1

END

ELSE

BEGIN

-- The file date is the same or older.

SET @IsNewFile = 0

END

END

ELSE

BEGIN

-- This is a new process for tbl_ImportFileCreateDate. Add a record to that table and set @IsNewFile to TRUE.

INSERT INTO tbl_ImportFileCreateDate (ProcessName, FileCreateDate)

VALUES (@ProcessName, @FileCreateDate)

SET @IsNewFile = 1

END

SELECT @IsNewFile

The relevant Global Variables in the package are defined as follows:
Name : Scope : Date Type : Value
FileCreateDate : (Package Name) : DateType : 1/1/2000
IsNewFile : (Package Name) : Boolean : False

Setting the properties in the "Execute SQL Task Editor" has been the difficult part of this. Here are the settings.

General
Name = Compare Last File Create Date
Description = Compares the create date of the current file with a value in tbl_ImportFileCreateDate.
TimeOut = 0
CodePage = 1252
ResultSet = None
ConnectionType = OLE DB
Connection = MyServerDataBase
SQLSourceType = Direct input
IsQueryStoredProcedure = False
BypassPrepare = True

I tried several SQL statements, suspecting it's a syntax issue. All of these failed, but with different error messages. These are the 2 most recent attempts based on posts I was able to locate.
SQLStatement = exec ? = dbo.p_CheckImportFileCreateDate 'GL Account Import', ?, ? output
SQLStatement = exec p_CheckImportFileCreateDate 'GL Account Import', ?, ? output

Parameter Mapping
Variable Name = User::FileCreateDate, Direction = Input, DataType = DATE, Parameter Name = 0, Parameter Size = -1
Variable Name = User::IsNewFile, Direction = Output, DataType = BYTE, Parameter Name = 1, Parameter Size = -1

Result Set is empty.
Expressions is empty.

When I run this in debug mode with this SQL statement ...
exec ? = dbo.p_CheckImportFileCreateDate 'GL Account Import', ?, ? output
... the following error message appears.

SSIS package "MyPackage.dtsx" starting.
Information: 0x4004300A at Import data from flat file to tbl_GLImport, DTS.Pipeline: Validation phase is beginning.

Error: 0xC002F210 at Compare Last File Create Date, Execute SQL Task: Executing the query "exec ? = dbo.p_CheckImportFileCreateDate 'GL Account Import', ?, ? output" failed with the following error: "No value given for one or more required parameters.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

Task failed: Compare Last File Create Date

Warning: 0x80019002 at GLImport: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (1) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.

SSIS package "MyPackage.dtsx" finished: Failure.

When the above is run tbl_ImportFileCreateDate does not get updated, so it's failing at some point when calling the procedure.

When I run this in debug mode with this SQL statement ...
exec p_CheckImportFileCreateDate 'GL Account Import', ?, ? output
... the tbl_ImportFileCreateDate table gets updated. So I know that data piece is working, but then it fails with the following message.

SSIS package "MyPackage.dtsx" starting.
Information: 0x4004300A at Import data from flat file to tbl_GLImport, DTS.Pipeline: Validation phase is beginning.

Error: 0xC001F009 at GLImport: The type of the value being assigned to variable "User::IsNewFile" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object.

Error: 0xC002F210 at Compare Last File Create Date, Execute SQL Task: Executing the query "exec p_CheckImportFileCreateDate 'GL Account Import', ?, ? output" failed with the following error: "The type of the value being assigned to variable "User::IsNewFile" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object.
". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Task failed: Compare Last File Create Date

Warning: 0x80019002 at GLImport: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (3) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.

SSIS package "MyPackage.dtsx" finished: Failure.

The IsNewFile global variable is scoped at the package level and has a Boolean data type, and the Output parameter in the stored procedure is defined as a Bit. So what gives?

The "Possible Failure Reasons" message is so generic that it's been useless to me. And I've been unable to find any examples online that explain how to do what I'm attempting. This would seem to be a very common task. My suspicion is that one or more of the settings in that Execute SQL Task node is bad. Or that there is some cryptic, undocumented reason that this is failing.

Thanks for your help.

View 5 Replies View Related

Compare The Value Of A Variable With Previous Variable From A Function ,reset The Counter When Val Changes

Oct 15, 2007

I am in the middle of taking course 2073B €“ Programming a Microsoft SQL Server 2000 Database. I noticed that in Module9: Implementing User-Defined Functions exercise 2, page 25; step 2 is not returning the correct answer.

Select employeeid,name,title,mgremployeeid from dbo.fn_findreports(2)

It returns manager id for both 2 and 5 and I think it should just return the results only for manager id 2. The query results for step 1 is correct but not for step 2.

Somewhere in the code I think it should compare the inemployeeid with the previous inemployeeid, and then add a counter. If the two inemployeeid are not the same then reset the counter. Then maybe add an if statement or a case statement. Can you help with the logic? Thanks!

Here is the code of the function in the book:

/*
** fn_FindReports.sql
**
** This multi-statement table-valued user-defined
** function takes an EmplyeeID number as its parameter
** and provides information about all employees who
** report to that person.
*/
USE ClassNorthwind
GO
/*
** As a multi-statement table-valued user-defined
** function it starts with the function name,
** input parameter definition and defines the output
** table.
*/
CREATE FUNCTION fn_FindReports (@InEmployeeID char(5))
RETURNS @reports TABLE
(EmployeeID char(5) PRIMARY KEY,
Name nvarchar(40) NOT NULL,
Title nvarchar(30),
MgrEmployeeID int,
processed tinyint default 0)
-- Returns a result set that lists all the employees who
-- report to a given employee directly or indirectly
AS
BEGIN
DECLARE @RowsAdded int
-- Initialize @reports with direct reports of the given employee
INSERT @reports
SELECT EmployeeID, Name = FirstName + ' ' + LastName, Title, ReportsTo, 0
FROM EMPLOYEES
WHERE ReportsTo = @InEmployeeID
SET @RowsAdded = @@rowcount
-- While new employees were added in the previous iteration
WHILE @RowsAdded > 0
BEGIN
-- Mark all employee records whose direct reports are going to be
-- found in this iteration
UPDATE @reports
SET processed = 1
WHERE processed = 0

-- Insert employees who report to employees marked 1
INSERT @reports
SELECT e.EmployeeID, Name = FirstName + ' ' + LastName , e.Title, e.ReportsTo, 0
FROM employees e, @reports r
WHERE e.ReportsTo = r.EmployeeID
AND r.processed = 1
SET @RowsAdded = @@rowcount
-- Mark all employee records whose direct reports have been
-- found in this iteration
UPDATE @reports
SET processed = 2
WHERE processed = 1
END
RETURN -- Provides the value of @reports as the result
END
GO

View 1 Replies View Related

Scripting: Dumb Q.. How Can I Store A DTS Variable Inside A Script Variable?

Nov 1, 2005

Hi

View 7 Replies View Related

Debug Error - Object Variable Or With Block Variable Not Set -

Feb 15, 2006

I keep getting this debug error, see my code below, I have gone thru it time and time agian and do not see where the problem is.  I have checked and have no  NULL values that I'm trying to write back.
~~~~~~~~~~~
Error:
System.NullReferenceException was unhandled by user code  Message="Object variable or With block variable not set."  Source="Microsoft.VisualBasic"
~~~~~~~~~~~~
My Code
Dim DBConn As SqlConnection
Dim DBAdd As New SqlCommand
Dim strConnect As String = ConfigurationManager.ConnectionStrings("ProtoCostConnectionString").ConnectionString
DBConn = New SqlConnection(strConnect)
DBAdd.CommandText = "INSERT INTO D12_MIS (" _
& "CSJ, EST_DATE, RECORD_LOCK_FLAG, EST_CREATE_BY_NAME, EST_REVIEW_BY_NAME, m2_1, m2_2_date, m2_3_date, m2_4_date, m2_5, m3_1a, m3_1b, m3_2a, m3_2b, m3_3a, m3_3b" _
& ") values (" _
& "'" & Replace(vbCSJ.Text, "'", "''") _
& "', " _
& "'" & Replace(tmp1Date, "'", "''") _
& "', " _
& "'" & Replace(tmpRecordLock, "'", "''") _
& "', " _
& "'" & Replace(CheckedCreator, "'", "''") _
& "', " _
& "'" & Replace(CheckedReviewer, "'", "''") _
& "', " _
& "'" & Replace(vb2_1, "'", "''") _
& "', " _
& "'" & Replace(tmp2Date, "'", "''") _
& "', " _
& "'" & Replace(tmp3Date, "'", "''") _
& "', " _
& "'" & Replace(tmp4Date, "'", "''") _
& "', " _
& "'" & Replace(vb2_5, "'", "''") _
& "', " _
& "'" & Replace(vb3_1a, "'", "''") _
& "', " _
& "'" & Replace(vb3_1b, "'", "''") _
& "', " _
& "'" & Replace(vb3_2a, "'", "''") _
& "', " _
& "'" & Replace(vb3_2b, "'", "''") _
& "', " _
& "'" & Replace(vb3_3a, "'", "''") _
& "', " _
& "'" & Replace(vb3_3b, "'", "''") _
& "')"
DBAdd.Connection = DBConn
DBAdd.Connection.Open()
DBAdd.ExecuteNonQuery()
DBAdd.Connection.Close()

View 2 Replies View Related

Transact SQL :: Insert Values From Variable Into Table Variable

Nov 4, 2015

CREATE TABLE #T(branchnumber VARCHAR(4000))

insert into #t(branchnumber) values (005)
insert into #t(branchnumber) values (090)
insert into #t(branchnumber) values (115)
insert into #t(branchnumber) values (210)
insert into #t(branchnumber) values (216)

[code]....

I have a parameter which should take multiple values into it and pass that to the code that i use. For, this i created a parameter and temporarily for testing i am passing some values into it.Using a dynamic SQL i am converting multiple values into multiple records as rows into another variable (called @QUERY). My question is, how to insert the values from variable into a table (table variable or temp table or CTE).OR Is there any way to parse the multiple values into a table. like if we pass multiple values into a parameter. those should go into a table as rows.

View 6 Replies View Related

How To Match The Date Variable And Character Variable

Oct 9, 2001

Hello,
I run the DTS to copy data from Progress to SQL Server. How can match/convert the date variables to check.
The field p-date as format 'mm-dd-year' . It has the value of 10/09/2001.
The field s-date as varchar format. It has the value 2001-10-09.
How can use the where condition ( Select ...... WHERE p-date = s-date.)

Thanks

View 1 Replies View Related

Object Variable Or With Block Variable Not Set (was Frank)

Mar 7, 2005

When trying to upsize an access database to sql server using the upsize wizard, I get the following error:

"Object variable or With block variable not set."

Any assistance is greatly appreciated.

View 3 Replies View Related







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