Using A Variable In An IN Predicate
Oct 3, 2007Anybody know how to do this?
"Select something from some table where id in (@IDlist)"
where @IDlist is a comma-separated list of values (or something top that effect)
Anybody know how to do this?
"Select something from some table where id in (@IDlist)"
where @IDlist is a comma-separated list of values (or something top that effect)
hi ,
what is the definition and difference between predicate and residual predicate.
give me some examples..Basically the columns used in where clause are called as predicates. Am i right.
I run statement down,result is "go". why goes,gone,going is not in the result?
SELECT ID, firstname, lastnameFROM [contain-1]WHERE CONTAINS(firstname, ' FORMSOF (INFLECTIONAL, go) ')
information table [contain-1]
ID firstname
1 go
2 goes
3 gone
4 going
what result this query?
SELECT productname
FROM product
WHERE CONTAINS(productname,'spread NEAR boysenberry' )
explain word "NEAR".
Thanks,mohsen
I run query down.result is null.
SELECT ID, firstname, lastname
FROM [contain-1]
WHERE CONTAINS(firstname, 'pooya NEAR yaser')
table [contains-1] information:
ID firstname
1 pooya
2 mehdi
3 peter
4 yaser
why result is null?
thanks,mohsen
I run query down.result is null.
SELECT ID, firstname, lastname
FROM [contain-1]
WHERE CONTAINS(firstname, 'pooya NEAR yaser')
table [contains-1] information:
ID firstname
1 pooya
2 mehdi
3 peter
4 yaser
5 pooyaandyaser
why result is null?
thanks,mohsen
I run query down.result is null.
Why is result null?
SELECT ID, firstnameFROM [contain-1]WHERE CONTAINS(firstname, 'yaser NEAR pooya')
table information:
ID firstname
1 ali
2 peter
3 yaser
4 yaserapooya
5 mehdi
Thanks,mohsen
Hi,i want to search record in a table where a varchar column is equal toa word or this word with the letter 's' or this word with the letter'e'.Today, i've this query :select * From Table Where Column = 'Word' or Column like 'Word[es]'I want to remove the 'or' of this query to have only one condition.Does someone know a solution to my problem.Excuse my poor english language.I hope you understand my problem and thks for solution.
View 2 Replies View RelatedHi everybody,
I have a problem using the CONTAINS predicate. I use the contains
predicate in a web page that students utilize to look for dissertations
stored in a database (MS 2000) of the library. The search is one
big textbox where students can perform any type of reaserch. For
instance, they can insert the author, the title or few keywords of a
dissertation. After they have clicked on the button Submit, the words
that they have inserted are filtered and combined (with AND) in
one string:
Example: miami, education --> 'Miami AND Education'
An example of the query that I need to perfrom is the Query Number 1:
select docnumber,Title
FROM [Log].[dbo].[DocTable1]
where contains(SearchColumn,'miami AND education') order by docnumber
SearchColumn is a field (varchar) that is the concatenation of various
fields such as Location, Title, Author, etc... that are contained in
the same table (See below for the description of the Table DocTable1).
I'm currently testing the search and I have figured out that the query described above does not work.
For example, the query should produce the same resultsof the following one, but it does not:
select docnumber
FROM [Log].[dbo].[DocTable1]
where contains(Location,'miami') AND
contains(Keywords,'education') order by docnumber
I need to implement the first query, but i can not understand why it
does not produce the same results of the second one. Any Ideas?
Thanks,
Christian
--------------------------------------------------------------
CREATE TABLE [DocTable1] (
[DocNumber] [int] NOT NULL ,
[LastName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[FirstName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Program] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Paper] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Location] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[ANNO] [int] NULL ,
[Title] [varchar] (350) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[TitleSort] [varchar] (350) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Keywords] [varchar] (350) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[FT] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[URL] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[SearchColumn] [varchar] (900) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
CONSTRAINT [PK_DocTable1] PRIMARY KEY CLUSTERED
(
[DocNumber]
) ON [PRIMARY] ,
CONSTRAINT [Title_Author_DocTable1] UNIQUE NONCLUSTERED
(
[Title],
[LastName],
[FirstName]
) ON [PRIMARY] ,
CONSTRAINT [FT-Constraint] CHECK NOT FOR REPLICATION ([FT] = 'Y' or [FT] = 'N')
) ON [PRIMARY]
GO
I am having problems with the following SQL statement. It works how I want it to work if I use = @SearchQuery but when I try to switch to LIKE I run into problems. I tried it the way it is shown below and I also tried LIKE '%'@SearchQuery'%' with no luck. Does this have something to do with the pattern to match being a parameter? How would I go about doing this correctly.
"SELECT server_info.*, network_adapter.* FROM server_info LEFT JOIN network_adapter " + "ON server_info.server_id = network_adapter.server_id WHERE " + DropDownList1.SelectedValue.ToString() + " LIKE '%@SearchQuery%'"
Thanks
HiI am having a debate with one of the Postgres developers (Tom Lane)according to him ms-sql does not implement predicatelocking(SERIALIZABLE).Where predicate locking is defined as (from the postgres help):"12.2.2.1. Serializable Isolation versus True Serializability"It states: "To guarantee true mathematical serializability, it isnecessary for a database system to enforce predicate locking, whichmeans that a transaction cannot insert or modify a row that would havematched the WHERE condition of a query in another concurrenttransaction"Now I put it to him that that is exactly what SERIALIZABLE does isMS-SQL.But his response was "Only for WHERE conditions that can be expressedas a simple range constraint."Now is he correct i.e SERIALIZABLE works "Only for WHERE conditionsthat can be expressed as a simple range constraint." ?Regards,Daniel RothMCSD.NET
View 8 Replies View Related am encountering the NO JOIN PREDICATE warning in a query plan for a particualr SQL statement. In poking around, I've come across psotings that mention the CU 4 for SQL Server 2005. The update applies to a KB article that addresses complex queries with an outer join.
But in my case, it's not an outer join causeing the problem - they are all left joins. Here is the piece of SQL that is running extremely slowly:
Code Snippet
UPDATE @TESTTABLE
SET [@TESTTABLE].SignInCancelledNoEMR =
(SELECT q.cnt FROM
(SELECT COUNT(*) AS cnt,cl.Clinic_id AS ClinicIDq,cl.CLINIC_REG_ID AS MarketIDq
FROM dbo.tblactivity AS t
LEFT JOIN [ERIIProduction].dbo.computer c on t.machineid = c.comp_windowsname
LEFT JOIN [ERIIProduction].dbo.clinic cl on cl.clinic_id = c.comp_clinic_id
LEFT JOIN [ERIIProduction].dbo.Region r ON cl.CLINIC_REG_ID = r.REG_ID
WHERE t.status = '1'
AND cast(checkindate as datetime) >= @startDate
AND cast(checkindate as datetime) < DATEADD(d, 1, @endDate)
AND cl.clinic_reg_id IN (SELECT Item FROM dbo.Split(@regionIDList,','))
AND NOT EXISTS (SELECT 1 FROM [ERIIProduction].dbo.VisitPatient vp WHERE (t.activityid = vp.VSPAT_GalvanonActivityID)) --AND (t.memberid = vp.VSPAT_GalvanonMemberID))
GROUP BY cl.Clinic_id,cl.CLINIC_REG_ID) AS q
WHERE q.ClinicIDq = ClinicID AND q.MarketIDq = MarketID)
Before I apply the CU and enable the trace flags, I'd like to know if there is something else I can do within the query itself to make it run faster. I've tried the OPTION(FORCE ORDER ) hint, but that doesn't have any effect on the queery run time.
And as a whole, the query cost relative to the entire batch jumped from 75% to 96%.
Granted the execution time of the entire batch dropped from 9 minutes to 1 minute, this query should not even take that long.
Thanks for any input...!
Hi guys,
I need to change some characters when reading the values of a certain columns, I am trying to use something like the code below, but the following error:
"Cannot use a CONTAINS or FREETEXT predicate on table 'JURNALTRANS' because it is not full-text indexed."
Code Snippet
CASE
WHEN Contains (JurnalTrans.DESCRIPTION, 'A') THEN Replace(JurnalTrans.DESCRIPTION,'A','A1')
WHEN Contains (JurnalTrans.DESCRIPTION, 'B') THEN Replace(JurnalTrans.DESCRIPTION,'B','B2')
ELSE JurnalTrans.DESCRIPTION
END AS 'Cost Description',
I am also trying something like this
Code SnippetSELECT DESCRIPTION AS 'X' FROM JURNALTRANS WHERE CONTAINS(DESCRIPTION, 'Y')
but getting the same error
"Cannot use a CONTAINS or FREETEXT predicate on table 'JURNALTRANS' because it is not full-text indexed."
Any help will be appreciated,
Thanks in advance,
Aldo.
I have a report in SQL that passes parameters at runtime entered by the user for two date ranges (beginning and ending). I'm trying to write a formula that will print a specific field *only if* the specified date range entered by the user is BETWEEN a specific value (like 200401). This is kind of reverse of a normal WHERE, BETWEEN clause.
I tried a standard BETWEEN predicate in my WHERE clause like:
IF '200401' BETWEEN ?BegPer and ?EndPer then salesanal.ptdbud01 else 0
But, it's returning an error that my Then statement is missing. I can't use a normal statement like 'IF ?BegPer >= '200401' and ?EndPer <= '200401', then.....' because users could enter a RANGE of periods, so it would be difficult to code all of the possible combinations this way. I'm actually doing this in Crystal, but if someone can give me a standard MSSQL example, I can translate that over to Crystal.
Thanks in advance,
Michelle
I have two tables. Table A has 2162 rows and table B has 101 rows. There isn't any join keys that I can join on these two tables. But I need everything from table B and only one column (Col1) from table A. It will result in a cross join and retruns 218362 (2162 * 101) rows, which is correct. But this takes about 30 seconds to complete. Any workaround to accomplish this? Optimizer shows no predicate joins on the Nested Loop and to me it is correct.
Here is what I have so far.
SELECT B.*, A.col1
FROM TableB B
LEFT JOIN TABLE A A
ON 1 = 1
I have been searching for an escape character or a way of escapingdouble quotes that are actually in a string that I am using in thecontains predicate.Here is an exampleselect *from tablewhere contains(field, '"he said "what is wrong", that is what hesaid"')I need the double quotes in the string because they are part of thetext. Of course, Fulltext search raises the errorServer: Msg 7631, Level 15, State 1, Line 1Syntax error occurred near 'what is wrong", that is what he said'.Expected ''''' in search condition '"he said "what is wrong", that iswhat he said"'.If I remove the double quotes, the search does not return the properresults.Thanks in advance for the helpBill
View 2 Replies View RelatedHi,
I am using Microsoft FullText search feature in my database for Searching
strings.
I want to use CASE statement in CONTAINS.
DECLARE @allowSearchALL int
SELECT [ID] ,[Source] ,[Description],name
FROM [Search]
WHERE CONTAINS( Source , '"mail"')
i know we can use CASE in WHERE clause...but dono how to use CONTAINS with
CASE.
My Requirement is
if @allowSearchALL is 1 then get all records otherwise use specified
hardcoded text "mail"
I have to use CONTAINS.
I would like use some thing like this,
SELECT [ID] ,[Source] ,[Description],name
FROM [Search]
WHERE Source = CASE WHEN @allowSearchALL = 1 THEN Source ELSE 'mail' END
This way i can map column name to same column name if @allowSearchALL = 1 .
I do not want to use multiple IF blocks like if ( )
begin
end
else if( )
begin
end
How this can be done in CONTAINS ? like WHERE CONTAINS(source, CASE ....ELSE
...END)
Please give me solution for this.
Thanks in advance
Hi,
What is the dowside of not using all uppercase for predicates and key words?
I cannot find to see a problem beside adhering to a clean coding convention. After all I already have color coding so what would be the uppercase for?
Same question for the semicolon ; at the end of a sql block. Is that real necessary not to get in trouble sometime down the road or is it a non-issue. I find like I am now a C# guys if I use these ;
Just curious, I find tedious to switch from all upper case to normal case all the time. And not forget to type the ;
Thanks,
Philippe
Thanks in advance....
Let me simplify what I'm trying to do....
Basically, I want to run the following query by using SqlDataSource.
SELECT data FROM table WHERE row in ('one', 'two', 'three')
Simple enough....
So, here's my code.....which obviously doesn't work properly.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnStr %>" SelectCommand="SELECT data FROM table WHERE row in (@username)">
<SelectParameters><asp:ControlParameter ControlID="TextBox1" Name="username" PropertyName="Text" Type="String" /></SelectParameters>
</asp:SqlDataSource>
<asp:Label ID="TextBox1" runat="server" Text="'one', 'two', 'three'" Width="125px" Visible="True"></asp:Label>
Is my SelectCommand correct? Thanks.
Hi, our application is failing sometimes, with some select queries. After making traces in the database, I found the following error: Missing join predicate.
I googled that, and I only found this useless tip:
Missing Join Predicate: Indicates whether or not the query in question has a join predicate. If not, this can cause the Query Optimizer to produce a less than optimized query plan. The fix to this is to add a join predicate.
So, I dont know what a join predicate is... maybe I used it, but I don't know it by that name.
Thanks!
Hey all,
I've a querie which inserts into a table, while joining on it. Something like:
insert into table1
(columnA,
columnB
)
select (columnA,columnB)
from table2
where columnA NOT EXIST(SELECT 1 from table1,table2 where table1.columnA!=table2.columnA)
As a rule of thumb, I avoid subselects and negative logic. However, sql2k seems to pick the fastest execution plan using this query, using a left anti semi join on that subselect. My question is this; what are the repercussions of inserting into a table when sql2k has already picked a query plan based on its stats? Is deadlocking possible? I haven't been able to find any evidence one way or the other. My objects are several million rows, so I am expecting some sort of side effect.
Any help would be greatly appreciated.
Regards,
-Kilka
Hi all.
I am a new SQL Profiler user trying to baseline our eCommerce site. I am receiving EventClass 80, Missing Join Predicate (hereinafter MJP), often enough to be concerned about what may happen during very high traffic. I have isolated the query, included at the bottom of this post (cleaned up). There is very little info on this event class out on the web. Version is SQL 2000, latest service pack. I know I don't have table DDL here; I'm just trying to get overall direction without causing you much work/time.
Issues:
1. Even though only the value of product_id in the HAVING clause changes, I do not always get the MJP. I would expect that a query without a JP is a query without a JP and it would be all-or-none.
2. Although it happens maybe 20-30 % of the time in production, I can’t make it happen in testing.
Questions:
Anyone have experience with MJPs? How about the issue of why it's sporadic? Can anyone shed light? Know of good links, etc?
Thanks!!
bbRichbb
SELECT
p.Product_Id,
MIN(ae.Enum_Value) AS color,
p.Product_Name,
p.Status_Code,
ps.Curr_Price,
s.Section_Id,
COUNT(ps.SWATCH_STATUS) AS total_available_colors
FROM
Attribute_Enum_Value ae
INNER JOIN Product_Attribute_Enum pae ON ae.Attribute_Value_Id = pae.Attribute_Value_Id
AND ae.Attribute_Type_Id = pae.Attribute_Type_Id
INNER JOIN Product p
INNER JOIN Section_Product sp ON p.Product_Id = sp.Product_Id
INNER JOIN Section s ON sp.Section_Id = s.Section_Id ON pae.Product_Id = p.Product_Id
INNER JOIN PRODUCT_SWATCH ps ON ae.Enum_Value = ps.Color_Attr
AND p.Product_Id = ps.PRODUCT_ID
WHERE
(pae.Attribute_Type_Id = 500001)
AND (p.Product_Class_Id = 2)
AND (p.Status_Code = 'ACTV')
AND (ps.SWATCH_STATUS = 'ACTV')
GROUP BY
p.Sequence_Number,
p.Product_Id,
p.Product_Name,
p.Status_Code,
ps.Curr_Price,
s.Section_Id
HAVING
(p.Product_Id = 1209645)
ORDER BY
p.Sequence_Number,
p.Product_Id
I believe query optimizer can leverage the predicate used to define the filtered index. But I came to a situation that's not true:
USE tempdb;
GO
IF OBJECT_ID('Employees') IS NOT NULL
DROP TABLE Employees;
GO
CREATE TABLE Employees
[Code] ....
If we take a look at the query plan. we'll find an unnecessary Nested Loop and Key Lookup operator there with the IS NULL predicate.
Ironically, If I change the IS NULL to IS NOT NULL in both the index and Query, everything goes fine.
I have to write one query to exclude data from partial string in the predicate.
Select * from table where col NOT in ('%abc%,%xyz%).
So the data where col value doesn't contain the ABC and xyz string value only should be selected. I am also getting xyz data in the result.
Good afternoon,
I'm trying to use a parameterin a way that RS seems to think is unnatural, and I'm wondering about a work around...
Normally I can use parameters like so:
select *
from foo
where fooValue > @myParameter
What I'd like to do instead is use a constant on the right of the predicate, and a parameter to define the column to measure against, like so:
select *
from foo
where @myParameter > 10
Or
select *
from foo
where @myParameter is not null
Any assist with this is greatly appreciated...
Thanks,
Brian
Hi all.
I am a new SQL Profiler user trying to baseline our eCommerce site. I am receiving EventClass
80, Missing Join Predicate (hereinafter MJP), often enough to be concerned about what may happen
during very high traffic. I have isolated the query, included at the bottom of this post
(cleaned up). There is very little info on this event class out on the web. Version is SQL
2000, latest service pack. I know I don't have table DDL here; I'm just trying to get overall
direction without causing you much work/time.
Issues:
1. Even though only the value of product_id in the HAVING clause changes, I do not always get
the MJP. I would expect that a query without a JP is a query without a JP and it would be
all-or-none.
2. Although it happens maybe 20-30 % of the time in production, I can€™t make it happen in
testing.
Questions:
Anyone have experience with MJPs? How about the issue of why it's sporadic? Can anyone shed
light? Know of good links, etc?
Thanks!!
bbRichbb
SELECT
p.Product_Id,
MIN(ae.Enum_Value) AS color,
p.Product_Name,
p.Status_Code,
ps.Curr_Price,
s.Section_Id,
COUNT(ps.SWATCH_STATUS) AS total_available_colors
FROM
Attribute_Enum_Value ae
INNER JOIN Product_Attribute_Enum pae ON ae.Attribute_Value_Id = pae.Attribute_Value_Id
AND ae.Attribute_Type_Id = pae.Attribute_Type_Id
INNER JOIN Product p
INNER JOIN Section_Product sp ON p.Product_Id = sp.Product_Id
INNER JOIN Section s ON sp.Section_Id = s.Section_Id ON pae.Product_Id = p.Product_Id
INNER JOIN PRODUCT_SWATCH ps ON ae.Enum_Value = ps.Color_Attr
AND p.Product_Id = ps.PRODUCT_ID
WHERE
(pae.Attribute_Type_Id = 500001)
AND (p.Product_Class_Id = 2)
AND (p.Status_Code = 'ACTV')
AND (ps.SWATCH_STATUS = 'ACTV')
GROUP BY
p.Sequence_Number,
p.Product_Id,
p.Product_Name,
p.Status_Code,
ps.Curr_Price,
s.Section_Id
HAVING
(p.Product_Id = 1209645)
ORDER BY
p.Sequence_Number,
p.Product_Id
I am looking to filter the query using the free text predicate Contains for one of the column that have dimensions of the items. The query is something like
Select * from sampletable
where contains(filtercolumn, 'Near("*cm , *cm , *cm , *Kg.",10,True)')
Data in the filtercolumn is something like 64cm x 25cm x 35cm = 10Kg.
The query do not return any data.I also tried running the below query to see if cm* can be searcher for, but with no result again
Select * from sampletable
where contains(filtercolumn,, '"cm*"')
If I do something like below, it does return all columns that have 35cm within the text.
Select * from sampletable
where contains(filtercolumn,, '"35cm"')
After monitoring using SQL profiler, i found that Missing join predicate event is happening a lot.
The problem is that profiler doesn't allow me to select the textdata to know which SQL statement is causing the issue.
I tried using the spid to check what's that process is running but the problem is that application is running many sqls so when i run
select PROGRAM_NAME,hostname,qt.text from sys.sysprocesses as sps1 CROSS APPLY sys.dm_exec_sql_text(sps1.sql_handle) AS qt
where spid=169
it gets me the SQL being run at that time not the one that causing the event.
Hi, I test the following sql statement, finding that an error ocurs:
Msg 7630, Level 15, State 2, Line 3
Syntax error near '"' in the full-text search condition '"dsg SDRGDG " OR "sdfsdfsdfsdafdsafdsfds'.
DECLARE @searchTerm NVARCHAR(40)
SET @searchTerm = '"dsg SDRGDG " OR "sdfsdfsdfsdafdsafdsfdsafdsafdsafsafdfdsafdf"';
SELECT [JobTitle], [JobDes], [OpenDate], j.[URLRef], c.[CompanyName], c.[URLRef], c.[URLSource]
FROM JobWanted AS j INNER JOIN
Company AS c ON c.CompanyID = j.CompanyID
WHERE CONTAINS((JobTitle, JobDes), @searchTerm)
It seems too lengthy string will cause an error for full-text engine. I find the sdfsdfsdfsdafdsafdsfdsafdsafdsafsafdfdsafdf is truncated as shown in error message.
How to avoid this issue? Could I configre this limination?
Thanks in advance.
Ricky.
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?
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
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.
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