Trouble Calling Function In View && Multi-Table Select...
Aug 13, 2007
How Do I fix View(below) or Multi-Table select(below) to use this Function to return distinct rows via qcParent_ID?
Following Function populates a field (with concat list of related titles) with other required fields:
Create Function [dbo].openItemsIntoList(@Delimeter varchar(15),@qcparent_ID varchar(1000))
Returns Varchar(8000) as
Begin
Declare @Lists as varchar(8000);
Select @Lists = '';
Select @Lists = @Lists + itemTitle + @Delimeter From z_QClocate_openAll_Qualifier
Where @qcParent_ID = qcParent_ID;
Return Substring(@Lists,1,len(@Lists)-len(@Delimeter));
End
works perfect against single table select (returning 54 distinct rows by qcParent_ID):
Select a.qcParent_ID, a.Facility, a.Modality, openItemListToFix
From dbo.a2_qcEntryForm a
JOIN (Select DISTINCT qcParent_ID, dbo.openItemsIntoList(' / AND ',qcParent_ID) as openItemListToFix FROM dbo.a3_qcItems2Fix) i
on a.qcParent_ID = i.qcParent_ID
But data is needed from 3 tables...
- Created a VIEW that returns all (82) rows (negating distinct of the function on qcParent_ID)
- Failed Miserably Integrating Function call into a multi-table select (inexperienced with complex joins)
This VIEW returns ALL (82) rows in table:
CREATE VIEW z_QClocate_openAll AS
SELECT dbo.a1_qcParent.qcStatus, dbo.a1_qcParent.qcAlert, dbo.a3_qcItems2Fix.qcParent_ID, dbo.a3_qcItems2Fix.qcEntryForm_ID,
dbo.a3_qcItems2Fix.itemComplete, dbo.a3_qcItems2Fix.itemTitle, dbo.a2_qcEntryForm.Facility, dbo.a2_qcEntryForm.Modality
FROM dbo.a1_qcParent INNER JOIN
dbo.a2_qcEntryForm ON dbo.a1_qcParent.qcParent_ID = dbo.a2_qcEntryForm.qcParent_ID INNER JOIN
dbo.a3_qcItems2Fix ON dbo.a2_qcEntryForm.qcEntryForm_ID = dbo.a3_qcItems2Fix.qcEntryForm_ID AND
dbo.a1_qcParent.qcParent_ID = dbo.a3_qcItems2Fix.qcParent_ID
WHERE (dbo.a1_qcParent.qcStatus = 'Awaiting Attn') AND (dbo.a3_qcItems2Fix.itemComplete = 0) OR
(dbo.a1_qcParent.qcStatus = 'In Process') OR
(dbo.a1_qcParent.qcStatus = 'Re-Opened')
Calling like this returns ALL 82 rows (negating the functions distinct):
Select a.qcParent_ID, a.qcStatus, a.qcAlert, a.itemComplete, a.Facility, a.Modality, openItemListToFix
From z_QClocate_openAll a
JOIN (Select DISTINCT qcParent_ID, dbo.openItemsIntoList(' / AND ',qcParent_ID) as openItemListToFix FROM dbo.a3_qcItems2Fix) i
on a.qcParent_ID = i.qcParent_ID
AND THEN THERES...
Failing miserably on Integrating the Function call into This SELECT ON MULTI-TABLES:
How to integrate the Function call:
JOIN (Select DISTINCT qcParent_ID, dbo.openItemsIntoList(' / AND ',qcParent_ID) as openItemListToFix FROM dbo.a3_qcItems2Fix) i
on a.qcParent_ID = i.qcParent_ID
into the multi-table Select relationships (while maintaining Where & Order By):
SELECT dbo.a1_qcParent.qcStatus, dbo.a1_qcParent.qcAlert, dbo.a3_qcItems2Fix.qcParent_ID, dbo.a3_qcItems2Fix.qcEntryForm_ID,
dbo.a3_qcItems2Fix.itemComplete, dbo.a3_qcItems2Fix.itemTitle, dbo.a2_qcEntryForm.Facility, dbo.a2_qcEntryForm.Modality
FROM dbo.a1_qcParent INNER JOIN
dbo.a2_qcEntryForm ON dbo.a1_qcParent.qcParent_ID = dbo.a2_qcEntryForm.qcParent_ID INNER JOIN
dbo.a3_qcItems2Fix ON dbo.a2_qcEntryForm.qcEntryForm_ID = dbo.a3_qcItems2Fix.qcEntryForm_ID AND
dbo.a1_qcParent.qcParent_ID = dbo.a3_qcItems2Fix.qcParent_ID
WHERE (dbo.a1_qcParent.qcStatus = 'Awaiting Attn') AND (dbo.a3_qcItems2Fix.itemComplete = 0) OR
(dbo.a1_qcParent.qcStatus = 'In Process') OR
(dbo.a1_qcParent.qcStatus = 'Re-Opened')
View 3 Replies
ADVERTISEMENT
Sep 6, 2007
I am using RS 2000. I have a multi select parameter where I can select multiple states by separating with a comma. I am trying to figure out how to incorporate an "All" parameter.
Query:
Select [name], city, state, zipcode
From Golf inner join charlist_to_table(@State,Default)f on State = f.str
Function:
CREATE FUNCTION charlist_to_table
(@list ntext,
@delimiter nchar(1) = N',')
RETURNS @tbl Table (listpos int IDENTITY(1, 1) NOT NULL,
str varchar(4000),
nstr nvarchar(2000)) AS
BEGIN
DECLARE @pos int,
@textpos int,
@chunklen smallint,
@tmpstr nvarchar(4000),
@leftover nvarchar(4000),
@tmpval nvarchar(4000)
SET @textpos = 1
SET @leftover = ''
WHILE @textpos <= datalength(@list) / 2
BEGIN
SET @chunklen = 4000 - datalength(@leftover) / 2
SET @tmpstr = @leftover + substring(@list, @textpos, @chunklen)
SET @textpos = @textpos + @chunklen
SET @pos = charindex(@delimiter, @tmpstr)
WHILE @pos > 0
BEGIN
SET @tmpval = ltrim(rtrim(left(@tmpstr, @pos - 1)))
INSERT @tbl (str, nstr) VALUES(@tmpval, @tmpval)
SET @tmpstr = substring(@tmpstr, @pos + 1, len(@tmpstr))
SET @pos = charindex(@delimiter, @tmpstr)
END
SET @leftover = @tmpstr
END
INSERT @tbl(str, nstr) VALUES (ltrim(rtrim(@leftover)),
ltrim(rtrim(@leftover)))
RETURN
END
GO
Anyone have any ideas?
Thanks,
Deb
View 5 Replies
View Related
Jul 23, 2005
I use a database that has user names stored in Encrypted format usingthe following API.Declare Sub Encrypt2 Lib "QPRO32.DLL" (ByVal Work As String, ByValPASSWORD As String)Every time i require the user name i have to again decrypt the nameusing the same function.My problem is that when i fetch a large number of records i have toloop through every record and call the encrypt function for eachrecord.Instead of binding the recordset to my control i need to loopthrough and fill my controlA MSHFlexGrid in Vb6.0.Is there a way out to this problem that will make my record populatiogfaster withoutout changing the current Encrypted users.Thanx in Advance
View 2 Replies
View Related
Jul 20, 2005
Hi!I have a scalar function that returns integer:xview (int)Now, I'm trying to build a procedure that has the following selectinside:select atr1, xview(atr2)from tablenameBut, I get the 'Invalid name' error when I try to execute thatprocedure.If I got it right, I must use user.fn_name() syntax, but I cannot usedbo.xview() inside my procedure since it means xview will always beexecuted as dbo, which is unaccaptable.I'm a bit confused, so any hint is very welcomed.Thanks!Mario.
View 4 Replies
View Related
Jun 1, 2015
i have a column with mulitple ids stored with commas . i want to pass ids and get data along with name from the table..how to get multiselect value in a variable in sql server functionÂ
View 4 Replies
View Related
Nov 19, 2012
I have a list of ClassID that is stored based on users multi select on a listview
For example ClassID might contain
301
302
303
304
Now I need to find InstructorID where classID matches all the value in the above list.
I am using this query
Code:
Dim assSQL = "Select InstructorID from ClassInstructors where ClassID = @P0"
For i = 1 To classIDs.Count - 1
assSQL &= " UNION Select InstructorID from ClassInstructors where ClassID = @P" & i.ToString
Next
[Code] ....
But the problem is the query is returning InstructorID where ClassID matches any of the ClassIDs. I want it to return Instructor ID where ClassID matches all of the ClassIDs in the string.
View 1 Replies
View Related
May 26, 2008
Anyone see a way to trick the optimizer into not scanning all tables involved in the view?
-- create two test tables
create table dbo.test1
(testID int, TestName varchar(10))
create table dbo.test2
(testID int, TestName varchar(10))
-- populate
declare @i int
set @i = 1000
while @i > 0
begin
insert into dbo.test1
select @i, '1.' + cast(@i as varchar(5))
set @i = @i - 1
end
insert into dbo.test2
select 1, '2.1' union all
select 2, '2.2'
go
-- create view
create view dbo.vw_Test
as
select1 as QueryID,
TestName
fromdbo.Test1
union all
select2 as QueryID,
TestName
fromdbo.Test2;
go
-- this works as i want, only scans table dbo.Test2
select *
fromdbo.vw_Test
whereQueryId = 2
-- joining to a table triggers scan of both tables in view:
declare @table table (QueryID int)
insert into @table
select 2;
selectvt.TestName
fromdbo.vw_Test vt
join@table t on
vt.QueryID = t.QueryID
Using the showplan I can see why the optimizer ends up scanning all tables, but maybe there is a way to force it to use the QueryID param evaluation earlier in the filtering.
Nathan Skerl
View 6 Replies
View Related
Oct 18, 2007
I'm creating a Multi-statement Table-Valued Function...
Is it possible to insert variables into the table? In other words, is it possible
to have something like
declare
@value1 varchar(10)
@value2 varchar(10)
BEGIN
<do some work on value1 and value2>
INSERT @returningTable
@value1, @value2
instead of
BEGIN
<do some work on value1 and value2>
INSERT @returningTable
SELECT col1, col2 from T_SOURCE
Here's why I want to insert variables...My function needs to return a table which contains a 'partial' incremental key.
I'll go with an example to explain what i have to do
Source_table
col1 col2
Mike 10
Mike 20
Ben 50
John 15
John 25
John 35
The table that my function needs to create should look like this
col1 col2 col3
Mike 10 1
Mike 20 2
Ben 50 1
John 15 1
John 25 2
John 35 3
I thought of creating a cursor and then looping through it generate col3 and save values of other individual columns in variables. But don't know how to use those variables when inserting records into function table.
Any other ideas? I'm caoming from Oracle world, I might be having some strange ideas on how to solve this problem. Any help is appreciated.
Thank you.
View 7 Replies
View Related
Jul 18, 2007
Hello everybody,
I need to create a function which takes a multi-value parameter. When I select more than one item, I get the error that I have too many arguments. Does anybody have a solution?
Or can I create a view and then do a "SELECT * FROM viewName WHERE columnName IN (@param)"?
Thanks in advance for your answers.
View 7 Replies
View Related
Apr 6, 2007
We are trying to create a TVF that executes a CLR Stored Procedure we wrote to use the results from the SP and transform them for the purposes of returning to the user as a table.
Code Snippet
[SqlFunction ( FillRowMethodName = "FillRow",
TableDefinition = "CustomerID nvarchar(MAX)",
SystemDataAccess = SystemDataAccessKind.Read,
DataAccess = DataAccessKind.Read,
IsDeterministic=false)]
public static IEnumerable GetWishlist () {
using (SqlConnection conn = new SqlConnection ( "Context Connection=true" )) {
List<string> myList = new List<string> ();
conn.Open ();
SqlCommand command = conn.CreateCommand ();
command.CommandText = "GetObject";
command.Parameters.AddWithValue ( "@map", "Item" );
command.CommandType = System.Data.CommandType.StoredProcedure;
using ( SqlDataReader reader = command.ExecuteReader ( System.Data.CommandBehavior.SingleRow )) {
if (reader.Read ()) {
myList.Add ( reader[0] as string );
}
}
return (IEnumerable)myList;
}
}
When command.ExecuteReader is called, I am getting an "Object not defined" error. However, the stored procedure can be used in SQL Management Studio just fine.
Code SnippetEXEC GetObject 'Item'
Is there some sorf of trick I am missing?
Thank you!
View 3 Replies
View Related
Jul 24, 2015
I have an SSRS report with several variables, some of which are multi-valued. Â The main query that feeds the report uses some table value functions. Â For example, the query looks something like this:
select tv1.a, tv1.b, tv2.x, tv2.y, tbl.m, tbl.n
from tableValueFunction1(@MultiValueParam) as tv1
inner join tableValueFunction2(@MultiValueParam) as tv2 on tv1.xxx = tv2.xxx
inner join regularTable as tbl on tv1.xxx = tbl.xxx
where tbl.abc in (@MultiValueParam).When I try to run this, I get an error saying that I'm feeding the wrong number of parameters into the table value functions. Â I've fed multi-valued parameters to stored procedures before and used a splitter function to split out the comma separated values, so I was planning to do the same thing in this scenario. Â However, this is different. Â When I look at the query in SQL Profiler, it shows discrete values for the multi value parameter. Â For example, the same query above looks like this when viewed through the profiler (using 1,2,3 as my multi-value selection):
select tv1.a, tv1.b, tv2.x, tv3.y, tbl.m, tbl.n
from tableValueFunction1(1,2,3) as tv1
inner join tableValueFunction2(1,2,3) as tv2 on tv1.xxx = tv2.xxx
inner join regularTable as tbl on tv1.xxx = tbl.xxx
where tbl.abc in (1,2,3)
In other words, SSRS isn't converting the multi-value parameter to a comma separated string, like it normally does.
View 2 Replies
View Related
Sep 5, 2007
what is more efficient between a table-value function or a View
View 3 Replies
View Related
Aug 24, 2007
Hi guys 'n gals,
I created a query, which makes use of a temp table, and I need the results to be displayed in a View. Unfortunately, Views do not support temp tables, as far as I know, so I put my code in a stored procedure, with the hope I could call it from a View....
I tried:
CREATE VIEW [qryMyView]
AS
EXEC pr_MyProc
and unfortunately, it does not let this run.
Anybody able to help me out please?
Cheers!
View 3 Replies
View Related
Nov 2, 2006
Hi all,
I've created a number of tables, views, sproc, and functions whose names begin with "sys_", but when I tried to create a multi-statement table-valued function with this type of name, I got:
Server: Msg 1706, Level 16, State 2, Procedure sys_tmp, Line 9
System table 'sys_test' was not created, because ad hoc updates to system catalogs are not enabled.
I had a quick look in this forum for 1706 (and on Google) but couldn't find anything. Does anyone know for certain if this is a bug in SQL2K?
Thanks, Jos
Here's a test script:
/*
----------------------------------------------------------------------------------------------------
T-SQL code to test creation of three types of function where the function name begins with "sys_".
Jos Potts, 02-Nov-2006
----------------------------------------------------------------------------------------------------
*/
PRINT @@VERSION
go
PRINT 'Scalar function with name "sys_" creates ok...'
go
CREATE FUNCTION sys_test
()
RETURNS INT
AS
BEGIN
RETURN 1
END
go
DROP FUNCTION sys_test
go
PRINT ''
go
PRINT 'In-line table-valued function with name "sys_" creates ok...'
go
CREATE FUNCTION sys_test
()
RETURNS TABLE
AS
RETURN SELECT 1 c
go
DROP FUNCTION sys_test
go
PRINT ''
go
PRINT 'Multi-statement table-valued function with name "sys_" generates error 1706...'
go
CREATE FUNCTION sys_tmp
()
RETURNS @t TABLE
(c INT)
AS
BEGIN
INSERT INTO @t VALUES (1)
RETURN
END
go
DROP FUNCTION sys_test
go
PRINT ''
go
/*
----------------------------------------------------------------------------------------------------
*/
And here€™s the output from running the test script in Query Analyser on our server:
Microsoft SQL Server 2000 - 8.00.2039 (Intel X86)
May 3 2005 23:18:38
Copyright (c) 1988-2003 Microsoft Corporation
Standard Edition on Windows NT 5.0 (Build 2195: Service Pack 4)
Scalar function with name "sys_" creates ok...
In-line table-valued function with name "sys_" creates ok...
Multi-statement table-valued function with name "sys_" generates error 1706...
Server: Msg 1706, Level 16, State 2, Procedure sys_tmp, Line 11
System table 'sys_tmp' was not created, because ad hoc updates to system catalogs are not enabled.
Server: Msg 3701, Level 11, State 5, Line 2
Cannot drop the function 'sys_test', because it does not exist in the system catalog.
View 3 Replies
View Related
Jul 23, 2005
I have a problem (who not?) with a function which i'm using in a view.This function is a function which calculates a integer value of adate. For example: '12/31/2004 00:00:00" becomes 20041231. This isvery handy in a datawarehouse and performes superfast. But here is myproblem.My calendar table is limited by a couple of years. What happens isthat sometimes a value is loaded which is not in the range of theCalendardate. What we want to do is when a date is loaded is that thisfunction insert a minimum date when date < minimum date and a maximumdate when date > maximum date.Yes i know you're thinking : This is datamanipulation and yes this istrue. But now we loose information in our cubes and reports by innerjoining. So if we can use a minimum and a maximum than a user wouldsay: "This is strange, a lot of values on 1980/1/1!" instead of "Ithink that i have not all the data!"GreetzHennie
View 2 Replies
View Related
Sep 21, 2006
Hey,First, sorry if this post appear twice, because, I can not find my postrecently send, trying to post it once again.I'm out of ideas, so, I thought, will search help here again :(I'm trying to prepare a view for ext. app. This is in normal cases veryeasy, but what if the view structure should be dynamic?!Here is my point (I will siplify the examples).I have a table:create table t_data (id bigint identity (1,1) not null,valvarchar(10) not null,data varchar(100) not nullconstraint [PK_t_data] primary key clustered(id) with fillfactor = 90 on [PRIMARY] )goinsert into t_data (val, data) values('1111111111','1234567890abcdefghijklmnoprstuvwxyz 1234567890abcdefghijklmnoprstuvwxyz67890abcdefghij klmnoprstuvwxyz')insert into t_data (val, data) values('2222222222','1234567890abcdefghijklmnoprstuvwxyz 1234567890abcdefghijklmnoprstuvwxyz12345abcdefghij klmnoprstuvwxyz')insert into t_data (val, data) values('3333333333','12345abcdefghijklmnoprstuvwxyz12345 67890abcdefghijklmnoprstuvwxyz1234567890abcdefghij klmnoprstuvwxyz')insert into t_data (val, data) values('4444444444','67890abcdefghijklmnoprstuvwxyz12345 67890abcdefg12345hijklmnoprstuvwxyz67890abcdefghij klmnoprstuvwxyz')insert into t_data (val, data) values('5555555555','1230abcdefghijklmnoprst12345uvwxyz1 234567890abcdefghijklmnoprstuvwxyz67890abcdefghijk lmnoprstuvwxyz')gocreate table t_dataVal (id bigint identity (1,1) not null,valvarchar(10) not null,fill varchar(4) not nullconstraint [PK_t_dataVal] primary key clustered(id) with fillfactor = 90 on [PRIMARY] )goinsert into t_dataVal (val, fill) values ('1111111111','AAAA')insert into t_dataVal (val, fill) values ('2222222222','KKKK')insert into t_dataVal (val, fill) values ('3333333333','DDDD')insert into t_dataVal (val, fill) values ('4444444444','ZZZZ')insert into t_dataVal (val, fill) values ('5555555555','CCCC')gocreate table t_conf (id bigint identity (1,1) not null,start int not null,length int not null,description varchar(20) not null,constraint [PK_t_conf] primary key clustered(id) with fillfactor = 90 on [PRIMARY] )goinsert into t_conf (start, length, description) values (1,10,'value_1')insert into t_conf (start, length, description) values (11,3,'value_2')insert into t_conf (start, length, description) values(55,15,'value_3')insert into t_conf (start, length, description) values (33,2,'value_4')insert into t_conf (start, length, description) values (88,1,'value_5')insert into t_conf (start, length, description) values (56,7,'value_6')goNow here is the issue:table t_conf contain data, which can be modified by user. The user isseting the appropriate values.Now, there should be a view, which returns:- as headers (collumn names) this what is defined in description columnof t_conf (for example: value_1, value_2 ... value_6)- as values, substrings of all data from t_data, cutted with start andlength values for appropriate decription from t_conf.- first two columns of view, should be column val and fill of t_dataValtableSo the effect should be like this:valfillvalue_1value_2value_3value_4value_5value61111111111AAAA1234567890abc....2222222222KKKK1234567890abc....3333333333DDDD12345abcdefgh....4444444444ZZZZ67890abcdefgh....5555555555CCCC1230abcdefghi....of course, for all other value_x should be the appropriate substringsshown.Sounds simple, hm?Well, I'm trying to do this, since yesterday evening, and can not :(In real life, the call of view/function might happend a lot.The table t_data might have around 4000 records, but the data string islonger (around 3000 characters).Application, might acess a udf, which returns table, and I was focusingin that.Was trying, to create local temp table in function, to insert values,using cursor over t_conf.Unfortunately, everything what I get, is just a vertical representationof the data, and I need it horizontal :(The other problem in function is, that I can not use exec() (wll known)so I can not even create a table,dynamicly, using as column names description value from table t_conf,and as size of field length from this table.Sorry, that the description is maybe not exactly for my problem, butthis is because I'm not even sure, which way to use :(any help will be appreciated!Thank You - Matik
View 1 Replies
View Related
Jul 23, 2005
Because of an error in google or underlying site i can reply on my ownissue. Therefore i copied the former entered message in this message.-------------------------------------REPY----------------------------------Hi Maybe i wasn't clear. I want to dynamically check whether what thelowest date and the highest date is in the calendar table. Thepresented solutions has fixed dates and i don't want that.If i could store a global variable in SQL server (dynamic properties?)then it would be great. Fill this once and call it multiple times inmy intensively used function. Is this possible?GreetzHennie----------------------------Previously enteredissue-----------------------I have a problem (who not?) with a function which i'm using in a view.This function is a function which calculates a integer value of adate. For example: '12/31/2004 00:00:00" becomes 20041231. This isvery handy in a datawarehouse and performes superfast. But here is myproblem.My calendar table is limited by a couple of years. What happens isthat sometimes a value is loaded which is not in the range of theCalendardate. What we want to do is when a date is loaded is that thisfunction insert a minimum date when date < minimum date and a maximumdate when date > maximum date.Yes i know you're thinking : This is datamanipulation and yes this istrue. But now we loose information in our cubes and reports by innerjoining. So if we can use a minimum and a maximum than a user wouldsay: "This is strange, a lot of values on 1980/1/1!" instead of "Ithink that i have not all the data!"GreetzHenniePlaats een reactie op dit berichtBericht 2 van deze discussieVan:John Bell (jbellnewsposts@hotmail.com)Onderwerp:Re: Intensively used function in view needs a minimum andmaximum from a tableView this article onlyDiscussies:comp.databases.ms-sqlserverDatum:2004-12-30 03:56:25 PSTHiIf you LEFT or RIGHT JOIN to the calendar table you will get a NULLvaluefor the column, you can then is CASE to determine the valueCREATE FUNCTION ConvertDate (@datevalue datetime)RETURNS INTASBEGINDECLARE @dateint INTSELECT @dateint = CAST( CASE WHEN A.Date < '20030101' THEN '19800101'WHEN A.Date > '20051231' THEN '99991231'ELSE CONVERT(CHAR(4),C.[Year]) + RIGHT('0'+CONVERT(VARCHAR(2),C.[Month]),2) + RIGHT('0'+CONVERT(VARCHAR(2),C.[Day]),2)END AS INT )FROM ( SELECT @datevalue AS [Date] ) ALEFT JOIN CALENDAR C ON C.[Date] = A.[Date]RETURN @dateintENDGOJohn"Hennie de Nooijer" <hdenooijer@hotmail.com> wrote in messagenews:191115aa.0412300238.7dee0f85@posting.google.c om...[color=blue]>I have a problem (who not?) with a function which i'm using in a[/color]view.[color=blue]> This function is a function which calculates a integer value of a> date. For example: '12/31/2004 00:00:00" becomes 20041231. This is> very handy in a datawarehouse and performes superfast. But here is my> problem.>> My calendar table is limited by a couple of years. What happens is> that sometimes a value is loaded which is not in the range of the> Calendardate. What we want to do is when a date is loaded is that this> function insert a minimum date when date < minimum date and a maximum> date when date > maximum date.>> Yes i know you're thinking : This is datamanipulation and yes this is> true. But now we loose information in our cubes and reports by inner> joining. So if we can use a minimum and a maximum than a user would> say: "This is strange, a lot of values on 1980/1/1!" instead of "I> think that i have not all the data!">> Greetz>> Hennie[/color]Plaats een reactie op dit berichtBericht 3 van deze discussieVan:Hugo Kornelis (hugo@pe_NO_rFact.in_SPAM_fo)Onderwerp:Re: Intensively used function in view needs a minimum andmaximum from a tableView this article onlyDiscussies:comp.databases.ms-sqlserverDatum:2004-12-30 15:32:06 PSTOn 30 Dec 2004 02:38:51 -0800, Hennie de Nooijer wrote:[color=blue]>I have a problem (who not?) with a function which i'm using in a[/color]view.[color=blue]>This function is a function which calculates a integer value of a>date. For example: '12/31/2004 00:00:00" becomes 20041231. This is>very handy in a datawarehouse and performes superfast. But here is my>problem.[/color](snip)Hi Hennie,Is this conversion all that your function does? If so, you might wanttotry the following alternative (using CURRENT_TIMESTAMP as example;replaceit with your date column / parameter):SELECT CAST(CONVERT(varchar, CURRENT_TIMESTAMP, 112) AS int)You could put this in the UDF (probably at least as fast as yourcurrentCalenmdar-table based function), or use it inline as a replacement tothefunction call (probably even faster).It should work for all dates from Jan 1st 1753 through Dec 31st 9999.Best, Hugo--(Remove _NO_ and _SPAM_ to get my e-mail address)
View 2 Replies
View Related
Jun 19, 2007
I am currently working on project where I need to insert, delete and update data from a text file I receive into multiple tables. So the file has multiple recordset types(50 to be exact) and each record has a a code to perform an -Update, Insert, or Delete to the destination table. Also when I receive the records they are not sorted. I need to sort the sets for each destination table and then read the the sorted set sequentially and perform the correct action.
Currently I am importing the record via flatfilesource into one column. I am using a script component here that would consist I guess 50 outputs including the fields needed for each table. The outputs are sorted by sortkey field and when I add the record to the output I perform data type transforms needed for each field(most are strings but I need to convert some dates, numbers ect..).
***is there a better way of accomplishing this?***
(ps. I could use the conditional split and the derive column into the 50 different table but it was giving me errors that were almost forcing me to use a nvarchar type instead of a varchar type during some of the field transformations.)
At this point I would need to read through each of the outputs sequentially and perform the update, insert or delete into the needed table. Would I have to create 50 script components with an ADO.net recordset adapter to update the tables for each of the outputs? I am hoping you can help come up with a better way to accomplish all of this.
Also if I do need to update the tables with the script component could someone point me to an example of how to programmatically accomplish that. Thanks for any help of suggestions that you may provide as I am feeling kind of stuck.
View 4 Replies
View Related
Aug 8, 2007
i created a query and when i run it like this i get data but when i add a value in the 2ed case for '2%' i get error.
Select a.email, case when a.reportnumber like '1%' then (select b.Reportnumber from ijasSummaryNo b where a.Reportnumber = b.Reportnumber) end as Reportnumber, case when a.Reportnumber like '1%' then (select b.stonebreakdown from ijasSummaryNo b where a.Reportnumber = b.Reportnumber) end as Measurement, case when a.Reportnumber like '1%' then (select b.reportcarddate from ijasSummaryNo b where a.Reportnumber = b.Reportnumber) end as ijasDate,
case when a.reportnumber like '2%' then (select c.Reportnumber from appraisalsummaryblue c where a.reportnumber = c.reportnumber) end as imacsRepNo
from t_RegisterInfoTemp a
Query works fine like this but when i add this (the one marked bold i get error)
case when a.reportnumber like '2%' then (select c.Reportnumber from appraisalsummaryblue c where a.reportnumber = c.reportnumber) end as imacsRepNo,case when a.reportnumber like '2%' then (select c.Measurement from appraisalsummaryblue c where a.reportnumber = c.reportnumber) end as Measurement2
This is the error.
Server: Msg 4414, Level 16, State 1, Line 1Could not allocate ancillary table for view or function resolution. The maximum number of tables in a query (260) was exceeded.
View 4 Replies
View Related
Oct 12, 2000
Hi all,
What's different from SELECT FROM A TABLE to SELECT FROM A VIEW? Which is faster? Can anyone explain my result following?
Example for:
-- TABLE:
set statistics io on
select * from TABLE_NAME
-->Table 'TABLE_NAME'. Scan count 2, logical reads 106, physical reads 0, read-ahead reads 0
-- VIEW:
Create view VIEW_NAME as SELECT * FROM TABLE_NAME
set statistics io on
select * from VIEW_NAME
-->Table 'TABLE_NAME'. Scan count 1, logical reads 53, physical reads 0, read-ahead reads 0.
View 2 Replies
View Related
Jul 20, 2005
Hello,I am trying to construct a query across 5 tables but primarily 3tables. Plan, Provider, ProviderLocation are the three primary tablesthe other tables are lookup tables for values the other tables.PlanID is the primary in Plan andPlanProviderProviderLocationLookups---------------------------------------------PlanIDProviderIDProviderIDLookupTypePlanNamePlanIDProviderStatusLookupKeyRegionIDLastName...LookupValue....FirstName...Given a PlanID I want all the Providers with a ProviderStatus = 0I can get the query to work just fine if there are records but what Iwant is if there are no records then I at least want one record withthe Plan information. Here is a sample of the Query:SELECT pln.PlanName, pln.PlanID, l3.LookupValue as Region,p.ProviderID, p.SSNEIN, pl.DisplayLocationOnPCP,pl.NoDisplayDate, pl.ProviderStatus, pl.InvalidDate,l1.LookupValue as ReasonMain, l2.LookupValue as ReasonSub,pl.InvalidDataFROM Plans plnINNER JOIN Lookups l3 ON l3.LookupType = 'REGN'AND pln.RegionID = l3.Lookupkeyleft outer JOIN Provider p ON pln.PlanID = p.PlanIDleft outer JOIN ProviderLocation pl ON p.ProviderID = pl.ProviderIDleft outer JOIN Lookups l1 ON l1.LookupType = 'PLRM'AND pl.ReasonMain = l1.LookupKeyleft outer JOIN Lookups l2 ON l2.LookupType = 'PLX1'AND pl.ReasonSub = l2.LookupkeyWHERE pln.PlanID = '123456789' AND pl.ProviderStatus = 0ORDER BY p.PlanID, p.ProviderID, pl.SiteLocationNumI know the problew the ProviderStatus on the Where clause is keepingany records from being returned but I'm not good enough at this toanother select.Can anybody give me some suggestions?ThanksDavid
View 5 Replies
View Related
Feb 26, 2007
Hi i'm new here so be kind.
Here is what I have.
Windows 2000 server, Sql server 2000 standard, Solomon 5.5
I have a view that is used by crystal reports. We had a company come in and they designed a custom report. The view uses three other views. The report works perfectly until two people try to run the report at the same time. This is when four of the columns in the report double the values.
We ran the report for a year or two with no problem. Now that we are starting to use Solomon Desktop for people out in the field we are finding this problem.
Is there a way that the view can be setup not to cause this problem?
View 10 Replies
View Related
Oct 22, 2007
I am trying to run the following code:
bcp "SELECT field1, field2, field3, field4*0.001 As field4calc
FROM table
ORDER BY field1, field2, field3"
queryout c:USERSMEDOCUMENTSfolderfile.txt -c -T
and i keep getting the following error:
Msg 102, Level 15, State 1, Line 10
Incorrect syntax near 'queryout'.
I have also tried to use bcp to export a view of the same data with the following code:
bcp [database].dbo.table.view out file.txt -c -T
To which I get the following error:
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near '.'.
What is the proper syntax for either of these? is something else going on?
View 3 Replies
View Related
Jun 8, 2006
Can anyone tell me how can I create a table in (SQL Server 2000) direct from a stored procedure execution or from a SELECT result?
I need something like this: CREATE TABLE < t > FROM <sp_name p1, p2, ...>or like this:
CREATE TABLE < t > FROM SELECT id, name FROM < w > ...
Thank you!
View 6 Replies
View Related
Dec 16, 2003
I have a SPROC that uses various VIEWs (passed into the SPROC from an ASP.NET dropdownlist), but I'm getting "Invalid Syntax near 'View name' " errors from the browser (IE) when I execute the dropdownlist.
It appears to me that it should work. The VIEWs run fine by themselves.
When I run the SPROC in Query Analyzer, I get the following error
Server: Msg 201, Level 16, State 4, Procedure Company_List_by_Filter, Line 0
Procedure 'Company_List_by_Filter' expects parameter '@Filter', which was not supplied.
I completely removed the control and rebuilt it (Using VisualStudio.NET 2003), but still have the same error.
VS builds the code without error.
Here's the code for the event handler:
private void Select_Filter_SelectedIndexChanged(object sender, System.EventArgs e)
{
SqlConnection myConnection = new SqlConnection("server=AMD;database=imSMART;Trusted_Connection=yes");
SqlDataAdapter myCommand = new SqlDataAdapter("Company_List_by_Filter", myConnection);
myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
myCommand.SelectCommand.Parameters.Add(new SqlParameter("@Filter", SqlDbType.VarChar, 150));
myCommand.SelectCommand.Parameters["@Filter"].Value = Select_Filter.SelectedValue;
//Arbitrary table name Company_List
DataSet ds = new DataSet();
myCommand.Fill(ds, "Company_List");
Select_Company.DataSource=ds.Tables["Company_List"].DefaultView;
Select_Company.DataBind();
}
Somehow the @Filter variable is not properly getting passed by the SPROC to the VIEW.
Anyone have any ideas why this is happening?
Thanks,
Paul
View 1 Replies
View Related
Aug 20, 2004
I have a pretty nasty situation in where I have two tables that hold quantity values for an interval of time. One table has an hourly date format while the other is every 5 minutes. I'm using the below t-sql to pull back the summed quantities I need in an HOURLY format; however, it is doubling the MarketQty field becuase it's not summing the qty field from the HE (henwood_extract) table correctly:
Here's a sample of what I'm trying to do.....
imo_meter_data table has records like this
Code:
ID END_DATE QTY
2 2004/08/18 00:05 2
2 2004/08/18 00:10 2.987
2 2004/08/18 00:15 3.1
henwood_extract is like this
Code:
ID END_DT QTY
132 2004/08/18 00:00 6.087
133 2004/08/18 00:00 1
I'm building a comparison tool, so I want the data from the query to return like this:
Code:
MyFDate MarketQty HenwoodQty
2004/08/18 00:00 7.087 7.087
Which would be correct if the sums worked in the query, but what it's looking like is this:
Code:
MyFDate MarketQty HenwoodQty
2004/08/18 00:00 14.174 14.174
Here's the query that I'm using:
Code:
select imo.meter_id, Convert(datetime, cast(datepart(mm, imo.end_date) as varchar)
+ '/' + cast(datepart(dd, imo.end_date) as varchar)
+ '/' + cast(datepart(yyyy, imo.end_date) as varchar)
+ ' ' + cast(datepart(hh, imo.end_date) as varchar)
+ ':00', 120) MyFDate,
sum(imo.qty) MarketQty, sum(he.qty) as HenwoodQty
from imo_meter_data imo, henwood_extract he where
convert(datetime, imo.end_date, 120) between
convert(datetime, '08/18/2004', 120) and
convert(datetime, '08/19/2004', 120) and
convert(datetime, he.end_dt, 120) between
convert(datetime, '08/18/2004', 120) and
convert(datetime, '08/19/2004', 120) and
convert(datetime, he.end_dt, 120) = Convert(datetime, cast(datepart(mm, imo.end_date) as varchar)
+ '/' + cast(datepart(dd, imo.end_date) as varchar)
+ '/' + cast(datepart(yyyy, imo.end_date) as varchar)
+ ' ' + cast(datepart(hh, imo.end_date) as varchar)
+ ':00', 120) and
he.plant_name = 'Brighton Beach' and
he.meter_type = 'ENERGY'
group by imo.meter_id, convert(datetime, cast(datepart(mm, imo.end_date) as varchar)
+ '/' + cast(datepart(dd, imo.end_date) as varchar)
+ '/' + cast(datepart(yyyy, imo.end_date) as varchar)
+ ' ' + cast(datepart(hh, imo.end_date) as varchar)
+ ':00', 120)
order by MyFDate
Any and all help is greatly appreciated.
View 3 Replies
View Related
Feb 27, 2008
I need to return a single, unique record for each director. In my example here, I'm getting back 5 records for Bossidy because he has 5 records in the Directorships table each with a unique CompID.
SELECT TDirectors.IDDir, TDirectors.DirFName, TDirectors.DirLName, TDirectors.DirLName + ', ' + TDirectors.DirFName AS DirFullName, TDirectors.ExecutiveTitle, TDirectors.DirGender, TDirectors.DirAge, TDirRace.DirRace,
TDirectors.PrincipalCompany AS CompanyName, TDirectorships.CompID
FROM TDirRace RIGHT OUTER JOIN
TDirectors ON TDirRace.IDDir = TDirectors.IDDir RIGHT OUTER JOIN
TDirectorships ON TDirectors.IDDir = TDirectorships.IDDir
WHERE (TDirectors.DirLName='Bossidy')
I thought I could do this but it doesn't work.
SELECT DISTINCT(TDirectors.IDDir)...
Thanks
View 5 Replies
View Related
Jul 20, 2005
I am having trouble using the CONTAINS function in sqlserver(enterprise manager). I am typing the following:Select *FROM mytableWHERE CONTAINS(myfield,'mystring')This returns the error:Query Designer encountered a MS Design Tools error:ODBC error:[Microsoft][ODBC SQL Server Driver]'CONTAINS' is not arecognizedfunction name.[Microsoft][ODBC SQL Server Driver][SQLServer]Statement(s) couldnot be prepared.According to the T-SQL reference on msdn this is a supported function?Am I typing something incorrectly? If this is not supported, isthere an equivalent to this function? In my field I have some commadelimited values ie 'apple,orange'. So I need to be able to discernwhich records contain orange. The LIKE keyword doesn't seem to workfor this scenario. Any help would be greatly appreciated.
View 3 Replies
View Related
Nov 20, 2007
Problem 1:
Suppose I have a table
T( A, B, C, D, E )
I want to retrieve D, E for all rows which have minimum C when we do a group by on A and B. The query would look something like
SELECT D, E FROM T HAVING C = MIN( C ) GROUP BY A, B
Unfortunately, SQL server gives the error that D, E are not in a group by clause. One way is:
SELECT T.D, T.E
FROM
T,
(
SELECT A, B, MIN( C ) AS F FROM T GROUP BY A, B
) AS T1
WHERE
T.A = T1.A AND
T.B = T1.B AND
T.C = T1.F
What I want to know is whether there is a simpler way of doing this or not, kinda like the first illegal query.
Problem 2:
Suppose in the query
SELECT A, B, CASE WHEN C = 'A' THEN 1
WHEN C = 'B' THEN 2 END ORDER
I want to do MIN( ORDER ). The simple way would be
SELECT A, B, MIN( CASE WHEN C = 'A' THEN 1
WHEN C = 'B'' THEN 2 END )
But this gives an error. There is a way:
SELECT T.A, T.B, MIN( T.C ) FROM
(
SELECT A, B, CASE WHEN C = 'A' THEN 1
WHEN C = 'B'' THEN 2 END AS C
) AS T
but I want to know if there is a simpler way to do this (kinda like the first illegal query).
Regards,
id
View 13 Replies
View Related
Mar 16, 2006
In SSIS 2005 what component can I use inside my Data Flow task to call my View and use it as a datasource? I know I've used an Execute T-SQL Task but I don't know what component to use inside an actual task itself. What I'm trying to do is in my Data Flow task, instead of using 3 OLE DB Source components, I want to actually call 3 stored procs and use those 3 components as the data sources to merge on using the merge and sort components later on
View 13 Replies
View Related
Sep 29, 2015
I have two databases DB1 and DB2 DB1 has a source table named 'Source' I have created a login 'Test_user' in DB2 with Public access. I have also created a view named 'Test_view' in DB2 which references data from DB1.dbo.Source
How can I do the following: AS A Test_user
SELECT * FROM DB2.dbo.Test_view --Should work
SELECT * FROM DB1.dbo.Source --Should Not work
View 2 Replies
View Related
Sep 29, 2015
I have two databases DB1 and DB2 DB1 has a source table named 'Source' I have created a login 'Test_user' in DB2 with Public access. I have also created a view named 'Test_view' in DB2 which references data from DB1.dbo.Source
How can I do the following: AS A Test_user
SELECT * FROM DB2.dbo.Test_view --Should work
SELECT * FROM DB1.dbo.Source --Should Not work
View 3 Replies
View Related
Nov 18, 2007
I'm a newb and this has been giving me a trouble for a while.
Code Block
SELECT class.classcode, classname, instrFirst, instrLast, csDay, CONVERT(nvarchar(30), csStart, 8), CONVERT(nvarchar(30), csEnd, 8)
FROM class, class_section, instructor
WHERE class.classcode = class_section.classcode
Group By className
Order By classname, csNum;
Msg 8120, Level 16, State 1, Line 1
Column 'class.classCode' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
class and instructor and class_section are their own tables but classcode and instrID are foreign keys on the class_section table. If anyone can explain this as clearly as possible that would be great (the help examples are usually too complicated)
View 6 Replies
View Related