DLookup Function In TSQL
May 24, 2008
Hi all,
Access has a DLookup function that allow you to look up a value in another table based on a criteria, how is this functionality achieved in TSQL?
Thanks
Regards
Melt
Hi all,
Access has a DLookup function that allow you to look up a value in another table based on a criteria, how is this functionality achieved in TSQL?
Thanks
Regards
Melt
Hi,
I need some pointers, I am trying to create a SQL function which will check to see if a column in a table will allow null values to be inserted.
I've tried searching the net but to no avail.
Kind Regards
Hey guys,
I have been trying to get a function to work but have been having a hard time. The tables that are used are a translation and validation tables. But the translation can be from different tables. What i would like the function to do is take in a 'description of a type' and a language code and send back the translated version. The issue is that the table is dynamic and there is my issue with my function.
ALTER FUNCTION [dbo].[Trans]
(
@Trans_description AS NVarchar(200),
@languageid AS nvarchar(10)
)
RETURNS nvarchar(50)
AS
BEGIN
DECLARE
@return AS nvarchar(50),
@TABLENAME AS nvarchar(50),
@sql AS nvarchar(100)
set @TableName = (select top(1) listtable from validationType where validationtypeDesc = @Trans_description)
SET @return =
(SELECT TOP (1) ValidationDesc FROM [translationvalidationlist] WHERE validationpartyid IN
(SELECT validationpartyid FROM @TableName WHERE validationtypePartyid IN
(select validationtypepartyid FROM validationtype WHERE validationtypeDesc = @Trans_description
))AND LANGUAGEID = @languageid)
RETURN @return
END
Is there anyway to do a @return = exec(@sql) of course sql would be the current @return. Right now i get the error Must declare the table variable "@TableName".
Thank you so much for all your help.
Hi guys,
I am looking for a solution to the problem described below (SQL SERVER 2000).
Thanks in advance for any help,
Aldo.
The script below:
Code Snippet
SELECT
Data.[Invoice No] AS 'InvoiceNo',
[JurnalTrans.REF2] AS 'JurnalTrans.REF2',
[JurnalTransMoves.SUF] AS 'JurnalTransMoves.SUF',
[RowIDDataLevel] AS 'RowIDDataLevel',
CASE WHEN RowIDDataLevel = 1 THEN CAST(Paid AS int) ELSE '0' END AS 'Paid' ,
CASE WHEN RowIDDataLevel = 1 THEN CAST([JurnalTransMoves.SUF] - [Paid] AS int) ELSE '0' END AS 'OutstandingBalance'
FROM CTE AS Data
INNER JOIN (SELECT [Invoice No], SUM([JurnalTransMoves.SUF]) AS Paid FROM CTE GROUP BY [Invoice No]) AS SUMSUF ON SUMSUF.[Invoice No] = DATA.[Invoice No]
ORDER BY [Accounts.ACCOUNTKEY], Data.[Invoice No], [RowIDDataLevel]
Gives these results:
Invoice No JurnalTrans.REF2 JurnalTransMoves.SUF RowIDDataLevel Paid OutstandingBalance
----------- ---------------- ---------------------- -------------- ----------- ------------------
5752 NULL 1155 1 1810 -655
5752 2032 400 2 0 0
5752 2033 155 3 0 0
5752 2034 100 4 0 0
5754 NULL 1732.5 1 2482 -750
5754 2035 750 2 0 0
16687 NULL 2555.8 1 2555 0
Where:
1810 (Paid) = 1155 + 400 + 155 + 100
2482 = 1732 + 750
and so on...
What I need is to get:
instead of 1810 ==> 655 = 400 + 155 + 100
instead of 2482 ==> 750
and so on...
In order to do that, I tried inserting "WHERE RowIDDataLevel Not In (1) " in the line:
Code Snippet
INNER JOIN (SELECT [Invoice No], SUM([JurnalTransMoves.SUF]) AS Paid FROM CTE WHERE RowIDDataLevel Not In (1) GROUP BY [Invoice No]) AS SUMSUF ON SUMSUF.[Invoice No] = DATA.[Invoice No]
and then getting the following:
InvoiceNo JurnalTrans.REF2 JurnalTransMoves.SUF RowIDDataLevel Paid OutstandingBalance
----------- ---------------- ---------------------- -------------- ----------- ------------------
5752 NULL 1155 1 655 500
5752 2032 400 2 0 0
5752 2033 155 3 0 0
5752 2034 100 4 0 0
5754 NULL 1732.5 1 750 982
5754 2035 750 2 0 0
That it is almost what I need, but not good enough because it makes the line marked in red to disappear because of RowIDDataLevel =1
16687 NULL 2555.8 1 2555 0
to disappear.
Hi All,
I need to find the highest of two numbers and lowest of the two numbers.
I read on the web that Greatest and least functions in sql can help me do that.
but when i use
greatest in my query it gives me this error
GREATEST is not a recognized built-in function name.
all I have is
declare @first int, @second int
set @first='12'
set @second='14'
select GREATEST(@first,@second)
Can somebody point me in the right direction.
Thanks so much
Hi guys,
I am using the LIKE function combined with a CASE WHEN to change a long list of words, but the list is too long...
Is there any posibility to insert more than one argument into one like function...?
Any other good ideas?
Below an example of the code I am using..
Thanks in advance,
Aldo.
Code Snippet
Case
WHEN JurnalTrans.DESCRIPTION LIKE '%myArgument01%' THEN 'Result'
WHEN JurnalTrans.DESCRIPTION LIKE '%myArgument02%' THEN 'Result'
WHEN JurnalTrans.DESCRIPTION LIKE '%myArgument03%' THEN 'Result'
WHEN JurnalTrans.DESCRIPTION LIKE '%myArgument04%' THEN 'Result'
ELSE ''
END AS 'Result'
Trying below instructions
create table t
(
indexvalue float
)
go
insert t
values (109.1)
insert t
values (109.3)
insert t
values (109.5)
insert t
values (109.9)
go
select *
from t
select sum (indexvalue) / count (*)
from t
select round (sum(indexvalue)/count (*), 1) -- this line is result of round (109.45) shows 109.4 that is incorrect
from t --why round function doesn't work correctly in this select
select round (109.45, 1) -- but this line results 109.5 that is correct
UPDATE 13_Together_Dec_final_ICNs SET [13_Together_Dec_final_ICNs].PL = Right(Nz(DLookUp("PH_LEVEL_02_CD","dbo_DIM_PRODUCT","PIN = '")),2)
WHERE ((([13_Together_Dec_final_ICNs].flag)="delete"));
How would I convert this to SQL SERVER 2005
I have a VB.NET Class called 'Approve' with a public function 'CanApprove' which returns a boolean value and accepts an input parameter of 'CurrentUserID' of type integer.
I want to use something like this that I have usedin Access with VBA:
lngID = Nz(DLookup("PermissionID", "tblPermissions", "ManagerID=" & UserID & " AND CurrentUserID=" & CurrentUserID & " AND Permission='A'"), 0)
So that if the person who is currently logged in has permissions over the person whose invoice he/she is viewing to approve, it will return a positive value so that if lngID > 0 then set CanApprove=false or vice versa.
How do I do this in ASP.net?
I have a multi value field into which I have placed several different values. I wish to compare a value that is entered by the user with the multi value field, to find if the value entered is there. I am assuming ( and also hoping) that I can use DLookUp to do this. At the moment I get all of the multi values returned by DlookUp and they are separated by commas and the value that I want to find is in there. However this is giving me an error because of the separating commas. How can I isolate/extract the value that I want so that I can make a comparison ? Is it something like MyFieldName.Value?
View 12 Replies View RelatedI am migrating a student database from Access to SQL Server. In AccessI have a query that displays grade information (grades are calculatedon a 12-point scale). In the query I average the students' scores andstore it in a column called Avg. I look up and display the equivalentgrade letter using Access' DLookup function from a table calledGradeTable_tbl. Here is how it's built in Access:Grade: DLookUp("[grade_letter]","GradeTable_tbl","[grade_num]= " &Int([Avg]))Here is the structure of the GradeTable_tbl:grade_num grade_letter0 F1 F2 D-3 D......10 B+11 A-12 AHow would I do the same thing in SQL Server? I want my output to besomething like:Student Score1 Score2 Score3 Avg GradeBob 12 10 8 10 B+Nancy 12 11 11 11 A-etc...I appreciate your feedback!-Paul------"You never know enough to know you don't know"
View 3 Replies View RelatedHi,
Does anybody knows how to create a DLOOKUP (dynamic lookup) in SSIS withour writing any kind of script?
I need to test records existance in destination from the source before inserting or updating in the destination (if the record exist in destination then update, else insert).
Any help apreciated.
I need to replace Access Val() functions with similiar function in sql.
i.e. Return 123 from the statement: SELECT functionname(123mls)
Return 4.56 from the satement: SELECT functionname(4.56tonnes)
Any one with ideas please
Thanks
George
Can anyone please give me the equivalent tsql for sql server 2000 for the following two queries which works fine in sql server 2005
1
-- Full Table Structure
select t.object_id, t.name as 'tablename', c.name as 'columnname', y.name as 'typename', case y.namewhen 'varchar' then convert(varchar, c.max_length)when 'decimal' then convert(varchar, c.precision) + ', ' + convert(varchar, c.scale)else ''end attrib,y.*from sys.tables t, sys.columns c, sys.types ywhere t.object_id = c.object_idand t.name not in ('sysdiagrams')and c.system_type_id = y.system_type_idand c.system_type_id = y.user_type_idorder by t.name, c.column_id
2
-- PK and Index
select t.name as 'tablename', i.name as 'indexname', c.name as 'columnname' , i.is_unique, i.is_primary_key, ic.is_descending_keyfrom sys.indexes i, sys.tables t, sys.index_columns ic, sys.columns cwhere t.object_id = i.object_idand t.object_id = ic.object_idand t.object_id = c.object_idand i.index_id = ic.index_idand c.column_id = ic.column_idand t.name not in ('sysdiagrams')order by t.name, i.index_id, ic.index_column_id
This sql is extracting some sort of the information about the structure of the sql server database[2005]
I need a sql whihc will return the same result for sql server 2000
I have this function in access I need to be able to use in ms sql. Having problems trying to get it to work. The function gets rid of the leading zeros if the field being past dosn't have any non number characters.For example:TrimZero("000000001023") > "1023"TrimZero("E1025") > "E1025"TrimZero("000000021021") > "21021"TrimZero("R5545") > "R5545"Here is the function that works in access:Public Function TrimZero(strField As Variant) As String Dim strReturn As String If IsNull(strField) = True Then strReturn = "" Else strReturn = strField Do While Left(strReturn, 1) = "0" strReturn = Mid(strReturn, 2) Loop End If TrimZero = strReturnEnd Function
View 3 Replies View RelatedHi all,
I executed the following sql script successfuuly:
shcInLineTableFN.sql:
USE pubs
GO
CREATE FUNCTION dbo.AuthorsForState(@cState char(2))
RETURNS TABLE
AS
RETURN (SELECT * FROM Authors WHERE state = @cState)
GO
And the "dbo.AuthorsForState" is in the Table-valued Functions, Programmabilty, pubs Database.
I tried to get the result out of the "dbo.AuthorsForState" by executing the following sql script:
shcInlineTableFNresult.sql:
USE pubs
GO
SELECT * FROM shcInLineTableFN
GO
I got the following error message:
Msg 208, Level 16, State 1, Line 1
Invalid object name 'shcInLineTableFN'.
Please help and advise me how to fix the syntax
"SELECT * FROM shcInLineTableFN"
and get the right table shown in the output.
Thanks in advance,
Scott Chang
I need to know how can i incoporate the functionality of DECODE function like the one in ORACLE in mSSQL..
please if anyone can help me out...
ali
Got some errors on this one...
Is Rand function cannot be used in the User Defined function?
Thanks.
I need to be able to pass the output of a function to another function as input, where all functions involved are user-defined in-line table-valued functions. I already posted this on Stack Exchange, so here is a link to the relevant code: [URL] ...
I am fairly certain OUTER APPLY is the core answer here; there's *clearly* some way in which does *not* do what I need, or I would not get the null output you see in the link, but it seems clear that there should be a way to fool it into working.
Hi,
I wonder if there a function that i can use in the expression builder that return a value (e.g o) if the input value is null ( Like ifnull(colum1,0) )
i hope to have the answer because i need it so much.
Maylo
Hello Friends, I am not sure if this is the right place to post this question but if not please suggest me when it can be posted.
I have been thinking of writing Stored procs in SQL CLR/ changing all of my Stored Procs to SQL CLR.
Is there any thing that I need to keep in mind about the size of the sotred proc (like calculation intensive) before I do that? I mean can even change a TSQL stored proc which is relatively small Stored Proc, that simply said Select * from Customers to SQL CLR? or the SQL CLR does only useful/makes difference with calculation intensive stored procs and big stored procs?
When I talked to our Architects they said every small sized stored proc can be written using SQL CLR and more over forget about the classic TSQL stored procs and get used to write SQL CLR when ever writing any database related stuff.
And also there are so many articles that discussed about the advantages of SQL CLR over the TSQL but I would appreciate if some one could put few bulletted points why do you think SQL CLR is more powerful.
Please advise.Thanks in advance,-L
Hi
I am creating some dynamic sql by passing variouse parametrs to my Stored Procedure. One of my Parameters is string has lots of values seperated by a comma to help build an 'IN' statement.
SET @SQL = 'SELECT * FROM areas'SET @p1 = '10,20'If @p1 IS NOT NULLBEGINSET @sSQL = @sSQL + ' WHERE (Areas IN (''' + Replace(@p1,',',''',''') + '''))'END
The above query runs perfecly well in Query Analyser, however when I put it into my ASP.NET application I get an error of "Error converting data type varchar to numeric."
So I think I need to do some sort of casting or Converting but im not sure how to do it. Or do I need to use a INSTRING?
I did manage to work out a method by using the follwoing
SELECT * FROM Areas WHERE PATINDEX('%,' + CAST(ArType AS VARCHAR) + ',%',',' + @p1 + ',') > 0
But I cant seem to convert the above line into coherent dynamic statement. My feeble attempt is below but I keep getting errors
SET @sql = @sql + ' WHERE PATINDEX(''%,'' + CAST(ArType AS VARCHAR) + '',%'','','' + @p1 + '','') > 0'
IM strugging to understand all the '''. My TSQL is pretty basic, any help would be much appreciated
Many thanks in advance
simple update, I want to update max_seq with max(0rdr_seq) from another table.
how do you?
update h
set max_seq = d.max(ordr_seq)
from h_drug_stage_dup h
join drug_ordr_stage d
on h.patkey = d.patkey and
h.ordr_dtm= d.ordr_dtm and
h.h_drug = d.h_Drug
Please see below ( in my sub-query I need to say settle_date = post_date +
3 business days )
How would this be done ? Pleas help !!!
declare @PD datetime, @MY_SD datetime
--SELECT @PD = SELECT POST_DATE FROM TRANSACTION_HISTORY
--select @MY_SD = @PD + 3 --T+3
--select @MY_SD = @MY_SD + case datepart(dw, @MY_SD) when 7 then 2 when 1 then 1 else 0 end*/
SELECT
WIRE_ORDER_NUMBER FROM TRANSACTION_HISTORY
WHERE POST_DATE BETWEEN '02/01/2001' AND '02/28/2001' AND
WIRE_ORDER_NUMBER IN
(
SELECT ORDER_NUMBER
FROM TRANSACTION_ARCHIVE WHERE TRANSACTION_ARCHIVE.ORDER_NUMBER = TRANSACTION_HISTORY.WIRE_ORDER_NUMBER
SETTLE_DATE = DATEADD(day, 3, POST_DATE ) case datepart(dw, POST_DATE) when 7 then 2 when 1 then 1 else 0 end))
Sql Server 7.0
==============
Hi all!
To find out the duplicate entries in a particular column,
I used the following tsql
select pno ,count(pno) from table1 group by pno
having count(pno)>1
But now I have another case where i have to test duplicity as a combination of 3 columns.
ie, for Eg :I have 3 columns with the following values.
colA colB colC
1 2 3===============row 1
1 3 5===============row 2
1 2 3===============row 3
1 4 5===============row 4
8 9 0===============row 5
I want to pick up all the duplicate rows(combo of colA,colB,colC)
duplicate rows here would be row 1 and row 3.
Can somebody give me a clue as to how to achieve this via TSQL.
Any help greatly appreciated.
TIA
Kinnu
HI,
I am creating a stored procedure where i need to update a table.
I have a field which has year as 2000-2001 i need to remove -2001
and just store it as 2000.I created a Procedure but i am getting an
error.
create PROCEDURE prdUpdate_Year
@year varchar(40)
As
@year = Mid(Newfiels,1,4)
UPDATE AddressBook SET AddressBook.Year = @year;
GO
Thanks
Hi,
I am trying to break up a column "name" into 2 columns "first name" and "last name". The name colum is currently "lastname, firstname". Is there an easy way to do this in SQL 6.5?
I successfully extracted the first name using:
firstname = rtrim(substring(name, (charindex(',', name)), 25))
But I am having trouble doing the lastname. Please help.
Thanks so much!
Laura
Hi,
I want to write a query which selects ind and
clcode where
ind(individual) has taken all 3 classes(clcode) 15, 16 and 17.
for example: it should only return data for ind 1 from the following data as only ind 1 has taken all three classes.
How can I write it?
table: ind_history
ind clcode
----------- -----------
1 16
1 17
2 17
1 15
2 16
3 11
4 15
I need help with a query that I want to incorporate into a scheduled DTS within SQL Server 2000. I have a process that brings in records from an Excel file, compares that day's records with any related information already stored in the database, then saves a table of joined records. This leaves me with any matches to the data. I need to filter out all but the most current record, which would be identified by a column named [DATE]. Ex:
Table tblMatchedRecords
M BLah Blah2 [DATE]
1 this that 20040101
2 this them 20040102
3 this that 20040630
In this example, I would like to have the record with [DATE] = 20040630 kept, and the others deleted. All columns do not always have to match exactly. I want to be able to specify which fields that need to match and pull only the latest date.
Make sense? Can anyone offer any suggestions?
I have a few variables declared
@amount=100000 (any big int)
@pamount=100000
@a1,@a2 - thorugh @25 -- each a bigint
@p1,@p2,@p3
@id - int
if @id is an odd number I need to randomly change @amount-@a1 (randomly to @a1 - @a25 so it ends up being any of 25 values)
and then @pamount randomly= to either @p1,@p2 or @p3
Can someone help me do the sql for this?
it will be within my stored procedure
Hi
Is there any sp or command to deactivate and activate all constraints in a database...
Thanks in Advance
RKNAIR
I have 2 sql server that are registered and linked.
If I have a table in server 1 that I want to make a backup of to server 2, how would I do that in t-sqlv(if the table did not already exisit on the second server)
Thanks
"Impossible is Nothing"
A stored procedure was running slowly so I took the code, removed thesubselect and included a join, then took the max and included as partof a correlated subquery.The result is below, however, this is no improvement over the original.An advice would be greatly appreciated.SELECT FSALT.FUNDING_LINE_TYPE_ID,A.PAYMENT_PERIOD_ID,A.CASH AS CASH,A.VOLUME AS VOLUMEFROM ACTUALS AINNER JOIN (SELECT MAX(COLLECTION_PAYMENT_PERIOD_*ID) AS CPP FROMACTUALS ACT WHERE COLLECTION_PAYMENT_PERIOD_ID<=*456) AS O ON O.CPP =A.COLLECTION_PAYMENT_PERIOD_IDINNER JOIN FS_ACTUAL_LINE_TYPES FSALT ON FSALT.FS_ACTUAL_LINE_TYPE_ID =A.FS_ACTUAL_LINE_TYPE_IDINNER JOIN PAYMENT_PERIODS PP ON PP.PAYMENT_PERIOD_ID =A.PAYMENT_PERIOD_IDWHEREA.ORG_ID=24771AND A.LSC_ORG_ID=5816AND PP.FUNDING_STREAM_ID=5AND PP.FUNDING_PERIOD_ID=6GROUP BYFSALT.FUNDING_LINE_TYPE_ID,A.PAYMENT_PERIOD_ID, A.CASH, A.VOLUME
View 2 Replies View Related