I'm trying to create a SQL server 2000 function that returns a scalar value, but I keep getting the error "Return statements in scalar valued functions must include an argument". Online clarification of this error message is no help at all.I've tried all sorts of combinations of the following, without much luck. Can someone point out my dim-witted mistake, please?ALTER FUNCTION dbo.intCoursesPublic (@intCatID as int) RETURNS intASBEGIN RETURN SELECT COUNT(intCourseID) AS Expr1 FROM dbo.tbl_guru_course_list WHERE (intCatID = @intCatID)END
How to include row values as columns in my select query. I have a table that stores comments for different sections in a web application. In the table below, I would like display each comment as a new column. I only want one row for each record_ID.
Existing table layout
table name - tblcomments Record_ID Comment_Section_ID Comment 1 5 Test 5 comment 1 7 Test 7 comment 2 5 New comment 2 7 Old comment 3 5 Stop 3 7 Go
Desired table layout table name - #tempComment Record_ID Comment_Section_5 Comment_Section_7 1 Test 5 comment Test 7 comment 2 New comment old comment 3 Stop Go
Once I figure out how to get the data in the layout above, I will need to join the table with my record table.
table name - tblRecord Record_ID Record_Type_ID Record_Status 1 23 Closed 2 56 Open 3 67 Open 4 09 Closed 5 43 In progress
I would like to be able to join the tables in the query below for the final output.
Select r.Record_ID, r.Record_Type_ID, r.Record_Status, c.Comment_Section_5, c.Comment_Section_7 from tblRecord r left outer join #tempComment c on r.record_ID = c.record_ID
How I can get the data in the desired #tempComment table layout mentioned above?
I thought this would be somewhat easy but I'm having trouble with this one. I have a statement that if 'ACTLABCOST' or 'ACTMATCOST' has a value of 0.00 then I need to make it .00.
I am trying to fill my table in different levels (hierarchy). The different levels are not properly processed. All layers now have the same value. It is intended that the layers are beaten flat. This implies multiple joins in order to be able to get the different levels.
'Ledgertableinterval' could be used to determine the hierarchy, but I did not come all the way out ...
So my suggestion is to fill with 1 character level 1, level 2 with 2 character and so on. If a level is not available anymore than filling up with higher level. For this you can use the replace function.
The DIM that I use;
USE [NJ] GO
/****** Object: Table [DIM].[FA] Script Date: 05/06/2015 09:57:24 ******/ SET ANSI_NULLS ON GO
SET QUOTED_IDENTIFIER ON GO CREATE TABLE [DIM].[FA](
but if my month is November and two months is added, the year does not change, it stays the same. how do I make the year change when two months are added toward the end of the year.
I have a simple script where I want to pull GLAcct, GLDesc and Amounts by Period. I want my results to look like attached snip.
I tried playing around with the dates; however, I'm receiving errors. Just to note that when I ran for 07/01/14 - 07/31/14 with the transaction date in where clause I was able to retrieve the correct results. Now I want to expand to get a view set up for the whole year....automation!
select gl_account.id as GLAcct, gl_account.descr as GLDesc, sum(gl_ledger.amount_n) as Net from gl_account
Can someone please explain how to do a query using the soundex function? If I have the last name of Smith and I want to get similar matches with soundex, what would be the syntax? SELECT * FROM NAME WHERE LNAME = 'SMITH' Thanks, Kellie
Has anyone used SOUNDEX() practically? Everytime i look through bol searching for a function i end up playing with soundex and diffference but have never been able (or wanted to take the time) to understand the values they generate..
We've installed this on our server: http://microsoft.apress.com/feature/72/sql-server-soundexing
(all the udf attempts were way too slow; this uda is nice and quick)
But we have not been able to reproduce the supposed improved functionality. No matter what misspelled name we send it, soundex and soundex_nara return the same amount of clients (in a db of over half a million). The return codes are sometimes different for the two functions but it doesnt ever result in an actual difference in query results. Has anyone actually experienced a difference in returned results?
EDIT: Have a look at this: http://en.wikipedia.org/wiki/Levenshtein_distance
I have two tables in Access database. One table has 166,000 rows and another -75,000 rows.
Both tables consist of the ids, names and addresses.
I need to run a program, which was written in VBA, to find similar names and cities in these two tables, and then I need to populate the third table with id only from both tables. I forgot to mention I use Soundex function in Access. I try to run this program for 48 hours, and it still running. Do you think this is a good idea to use Access for this task ? Or could you please help me to find another solution?
Hello, Does the SOUNDEX function only apply to english (surnames) or can it be used for other languages e.g. Dutch. Well, it can be used ofc. but does it produce meaningful output ?
Disgruntled with Soundex I went looking for a better phonetic matching algorithm.
Turns out there is a rather good one called Metaphone, which comes in two variants (Simple and Double)
I could find the source for this in C++, but I wanted to have it as a user function.
So here it is:
CREATE FUNCTION dbo.Metaphone(@str as varchar(70)) RETURNS varchar (25) /* Metaphone Algorithm
Created by Lawrence Philips. Metaphone presented in article in "Computer Language" December 1990 issue. Translated into t-SQL by Keith Henry (keithh_AT_lbm-solutions.com)
*********** BEGIN METAPHONE RULES *********** Lawrence Philips' RULES follow: The 16 consonant sounds: |--- ZERO represents "th" | B X S K J T F H L M N P R 0 W Y Drop vowels
Exceptions: Beginning of word: "ae-", "gn", "kn-", "pn-", "wr-" ----> drop first letter Beginning of word: "x" ----> change to "s" Beginning of word: "wh-" ----> change to "w" Beginning of word: vowel ----> Keep it
Transformations: B ----> B unless at the end of word after "m", as in "dumb", "McComb"
C ----> X (sh) if "-cia-" or "-ch-" S if "-ci-", "-ce-", or "-cy-" SILENT if "-sci-", "-sce-", or "-scy-" K otherwise, including in "-sch-"
D ----> J if in "-dge-", "-dgy-", or "-dgi-" T otherwise
F ----> F
G ----> SILENT if in "-gh-" and not at end or before a vowel in "-gn" or "-gned" in "-dge-" etc., as in above rule J if before "i", or "e", or "y" if not double "gg" K otherwise
H ----> SILENT if after vowel and no vowel follows or after "-ch-", "-sh-", "-ph-", "-th-", "-gh-" H otherwise
J ----> J
K ----> SILENT if after "c" K otherwise
L ----> L
M ----> M
N ----> N
P ----> F if before "h" P otherwise
Q ----> K
R ----> R
S ----> X (sh) if before "h" or in "-sio-" or "-sia-" S otherwise
T ----> X (sh) if "-tia-" or "-tio-" 0 (th) if before "h" silent if in "-tch-" T otherwise
V ----> F
W ----> SILENT if not followed by a vowel W if followed by a vowel
X ----> KS
Y ----> SILENT if not followed by a vowel Y if followed by a vowel
Z ----> S */
AS BEGIN Declare@Result varchar(25), @str3char(3), @str2 char(2), @str1 char(1), @strp char(1), @strLen tinyint, @cnt tinyint
set @strLen = len(@str) set@cnt=1 set@Result=''
--Process beginning exceptions set @str2 = left(@str,2) if @str2 in ('ae', 'gn', 'kn', 'pn', 'wr') begin set @str = right(@str , @strLen - 1) set @strLen = @strLen - 1 end if@str2 = 'wh' begin set @str = 'w' + right(@str , @strLen - 2) set @strLen = @strLen - 1 end set @str1 = left(@str,1) if @str1= 'x' begin set @str = 's' + right(@str , @strLen - 1) end if @str1in ('a','e','i','o','u') begin set @str = right(@str , @strLen - 1) set @strLen = @strLen - 1 set@Result=@str1 end
while @cnt <= @strLen begin set @str1 = substring(@str,@cnt,1) if @cnt <> 1 set@strp=substring(@str,(@cnt-1),1) elseset@strp=' '
if @strp<> @str1 begin set @str2 = substring(@str,@cnt,2)
if @str1in('f','j','l','m','n','r') set@Result=@Result + @str1
if @str1='q'set @Result=@Result + 'k' if @str1='v'set @Result=@Result + 'f' if @str1='x'set @Result=@Result + 'ks' if @str1='z'set @Result=@Result + 's'
if @str1='b' if @cnt = @strLen if substring(@str,(@cnt - 1),1) <> 'm' set@Result=@Result + 'b' else set@Result=@Result + 'b'
if @str1='c'
if @str2 = 'ch' or substring(@str,@cnt,3) = 'cia' set@Result=@Result + 'x' else if @str2in('ci','ce','cy')and@strp<>'s' set@Result=@Result + 's' elseset@Result=@Result + 'k'
if @str1='d' if substring(@str,@cnt,3) in ('dge','dgy','dgi') set@Result=@Result + 'j' elseset@Result=@Result + 't'
if @str1='g' if substring(@str,(@cnt - 1),3) not in ('dge','dgy','dgi','dha','dhe','dhi','dho','dhu') if @str2 in ('gi', 'ge','gy') set@Result=@Result + 'j' else if(@str2<>'gn') or ((@str2<> 'gh') and ((@cnt + 1) <> @strLen)) set@Result=@Result + 'k'
if @str1='h' if (@strp not in ('a','e','i','o','u')) and (@str2 not in ('ha','he','hi','ho','hu')) if@strp not in ('c','s','p','t','g') set@Result=@Result + 'h'
if @str1='k' if @strp <> 'c' set@Result=@Result + 'k'
if @str1='p' if @str2 = 'ph' set@Result=@Result + 'f' else set@Result=@Result + 'p'
if @str1='s' if substring(@str,@cnt,3) in ('sia','sio') or @str2 = 'sh' set@Result=@Result + 'x' elseset@Result=@Result + 's'
if @str1='t' if substring(@str,@cnt,3) in ('tia','tio') set@Result=@Result + 'x' else if@str2='th' set@Result=@Result + '0' else if substring(@str,@cnt,3) <> 'tch' set@Result=@Result + 't'
if @str1='w' if @str2 not in('wa','we','wi','wo','wu') set@Result=@Result + 'w'
if @str1='y' if @str2 not in('ya','ye','yi','yo','yu') set@Result=@Result + 'y' end set @cnt=@cnt + 1 end RETURN @Result END
Hi AllWe are using soundex (and later tried Nysiis) for fuzzy name searchsoftware. But we faced a lot of problems the search accuracy was not verygood also we saw a lot of misses of relevant names.There are many problems other than precision and accuracy, with soundex andNYSIIS.e.g.Look for Smith and it will come-up with around 250 very popular last names.That dones not help much when a user is searching for "John Smith". Also, itdoes not return Creighton for Kryton as the search string.I googled a little and saw soming called NamiX. Without contacting thecompany ( arizcon.com ) directly, I wanted to get feedback from newsgroupsor people who are experts at this. Has anyone used this software? If so, Isit as good as they claim?Thanks a million in advance.Steve Creighton(please remove .antispam from email address) or post back your answers tothis group
We have an application we are developing that will run worldwide. When we are searching data for peoples names I would like to use Soundex but I am not sure it works effectivly for any language other than English. Does anyone know if it is effective in Dutch, German, French etc?
I need to compare movie names from two systems. In both systems these names are entered manually by operators. I would like to compare them and give a rating on how close these names are equal.
Stripping special characters, and spaces is just not enough. It can happen that they key in sligthly different names. I've tried to use soundex but as we have over 15000 movie titles over the years i'm getting to many equal soundexes to use this as a comparison key.
Hi thereI have this query in a stored procedureSELECT * FROM Product WHERE FREETEXT (*, @SearchString )When I run the query with the @SearchString = 'hoover' it return values but if I spelt it wrong (eg: hover) I have no value returnMy question is, How can I use the SOUNDEX in a full text searchRegards
I was playing around with the new SQL 2005 CLR functionality andremembered this discussion that I had with Erland Sommarskog concerningperformance of scalar UDFs some time ago (See "Calling sp_oa* infunction" in this newsgroup). In that discussion, Erland made thefollowing comment about UDFs in SQL 2005:[color=blue][color=green]>>The good news is that in SQL 2005, Microsoft has addressed several of[/color][/color]these issues, and the cost of a UDF is not as severe there. In fact fora complex expression, a UDF in written a CLR language may be fasterthanthe corresponding expression using built-in T-SQL functions.<<I thought the I would put this to the test using some of the same SQLas before, but adding a simple scalar CLR UDF into the mix. The testinvolved querying a simple table with about 300,000 rows. Thescenarios are as follows:(A) Use a simple CASE function to calculate a column(B) Use a simple CASE function to calculate a column and as a criterionin the WHERE clause(C) Use a scalar UDF to calculate a column(D) Use a scalar UDF to calculate a column and as a criterion in theWHERE clause(E) Use a scalar CLR UDF to calculate a column(F) Use a scalar CLR UDF to calculate a column and as a criterion inthe WHERE clauseA sample of the results is as follows (time in milliseconds):(295310 row(s) affected)A: 1563(150003 row(s) affected)B: 906(295310 row(s) affected)C: 2703(150003 row(s) affected)D: 2533(295310 row(s) affected)E: 2060(150003 row(s) affected)F: 2190The scalar CLR UDF function was significantly faster than the classicscalar UDF, even for this very simple function. Perhaps a more complexfunction would have shown even a greater difference. Based on this, Imust conclude that Erland was right. Of course, it's still faster tostick with basic built-in functions like CASE.In another test, I decided to run some queries to compare built-inaggregates vs. a couple of simple CLR aggregates as follows:(G) Calculate averages by group using the built-in AVG aggregate(H) Calculate averages by group using a CLR aggregate that similatesthe built-in AVG aggregate(I) Calculate a "trimmed" average by group (average excluding highestand lowest values) using built-in aggregates(J) Calculate a "trimmed" average by group using a CLR aggregatespecially designed for this purposeA sample of the results is as follows (time in milliseconds):(59 row(s) affected)G: 313(59 row(s) affected)H: 890(59 row(s) affected)I: 216(59 row(s) affected)J: 846It seems that the CLR aggregates came with a significant performancepenalty over the built-in aggregates. Perhaps they would pay off if Iwere attempting a very complex type of aggregation. However, at thispoint I'm going to shy away from using these unless I can't find a wayto do the calculation with standard SQL.In a way, I'm happy that basic SQL still seems to be the fastest way toget things done. With the addition of the new CLR functionality, Isuspect that MS may be giving us developers enough rope to comfortablyhang ourselves if we're not careful.Bill E.Hollywood, FL------------------------------------------------------------------------- table TestAssignment, about 300,000 rowsCREATE TABLE [dbo].[TestAssignment]([TestAssignmentID] [int] NOT NULL,[ProductID] [int] NULL,[PercentPassed] [int] NULL,CONSTRAINT [PK_TestAssignment] PRIMARY KEY CLUSTERED([TestAssignmentID] ASC)--Scalar UDF in SQLCREATE FUNCTION [dbo].[fnIsEven](@intValue int)RETURNS bitASBEGINDeclare @bitReturnValue bitIf @intValue % 2 = 0Set @bitReturnValue=1ElseSet @bitReturnValue=0RETURN @bitReturnValueEND--Scalar CLR UDF/*using System;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;using Microsoft.SqlServer.Server;public partial class UserDefinedFunctions{[Microsoft.SqlServer.Server.SqlFunction(IsDetermini stic=true,IsPrecise=true)]public static SqlBoolean IsEven(SqlInt32 value){if(value % 2 == 0){return true;}else{return false;}}};*/--Test #1--Scenario A - Query with calculated column--SELECT TestAssignmentID,CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END ASCalcColumnFROM TestAssignment--Scenario B - Query with calculated column as criterion--SELECT TestAssignmentID,CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END ASCalcColumnFROM TestAssignmentWHERE CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END=1--Scenario C - Query using scalar UDF--SELECT TestAssignmentID,dbo.fnIsEven(TestAssignmentID) AS CalcColumnFROM TestAssignment--Scenario D - Query using scalar UDF as crierion--SELECT TestAssignmentID,dbo.fnIsEven(TestAssignmentID) AS CalcColumnFROM TestAssignmentWHERE dbo.fnIsEven(TestAssignmentID)=1--Scenario E - Query using CLR scalar UDF--SELECT TestAssignmentID,dbo.fnIsEven_CLR(TestAssignmentID) AS CalcColumnFROM TestAssignment--Scenario F - Query using CLR scalar UDF as crierion--SELECT TestAssignmentID,dbo.fnIsEven_CLR(TestAssignmentID) AS CalcColumnFROM TestAssignmentWHERE dbo.fnIsEven(TestAssignmentID)=1--CLR Aggregate functions/*using System;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;using Microsoft.SqlServer.Server;[Serializable][Microsoft.SqlServer.Server.SqlUserDefinedAggregate (Format.Native)]public struct Avg{public void Init(){this.numValues = 0;this.totalValue = 0;}public void Accumulate(SqlDouble Value){if (!Value.IsNull){this.numValues++;this.totalValue += Value;}}public void Merge(Avg Group){if (Group.numValues > 0){this.numValues += Group.numValues;this.totalValue += Group.totalValue;}}public SqlDouble Terminate(){if (numValues == 0){return SqlDouble.Null;}else{return (this.totalValue / this.numValues);}}// private accumulatorsprivate int numValues;private SqlDouble totalValue;}[Serializable][Microsoft.SqlServer.Server.SqlUserDefinedAggregate (Format.Native)]public struct TrimmedAvg{public void Init(){this.numValues = 0;this.totalValue = 0;this.minValue = SqlDouble.MaxValue;this.maxValue = SqlDouble.MinValue;}public void Accumulate(SqlDouble Value){if (!Value.IsNull){this.numValues++;this.totalValue += Value;if (Value < this.minValue)this.minValue = Value;if (Value > this.maxValue)this.maxValue = Value;}}public void Merge(TrimmedAvg Group){if (Group.numValues > 0){this.numValues += Group.numValues;this.totalValue += Group.totalValue;if (Group.minValue < this.minValue)this.minValue = Group.minValue;if (Group.maxValue > this.maxValue)this.maxValue = Group.maxValue;}}public SqlDouble Terminate(){if (this.numValues < 3)return SqlDouble.Null;else{this.numValues -= 2;this.totalValue -= this.minValue;this.totalValue -= this.maxValue;return (this.totalValue / this.numValues);}}// private accumulatorsprivate int numValues;private SqlDouble totalValue;private SqlDouble minValue;private SqlDouble maxValue;}*/--Test #2--Scenario G - Average Query using built-in aggregate--SELECT ProductID, Avg(Cast(PercentPassed AS float))FROM TestAssignmentGROUP BY ProductIDORDER BY ProductID--Scenario H - Average Query using CLR aggregate--SELECT ProductID, dbo.Avg_CLR(Cast(PercentPassed AS float)) AS AverageFROM TestAssignmentGROUP BY ProductIDORDER BY ProductID--Scenario I - Trimmed Average Query using built in aggregates/setoperations--SELECT A.ProductID,CaseWhen B.CountValues<3 Then NullElse Cast(A.Total-B.MaxValue-B.MinValue ASfloat)/Cast(B.CountValues-2 As float)End AS AverageFROM(SELECT ProductID, Sum(PercentPassed) AS TotalFROM TestAssignmentGROUP BY ProductID) ALEFT JOIN(SELECT ProductID,Max(PercentPassed) AS MaxValue,Min(PercentPassed) AS MinValue,Count(*) AS CountValuesFROM TestAssignmentWHERE PercentPassed Is Not NullGROUP BY ProductID) BON A.ProductID=B.ProductIDORDER BY A.ProductID--Scenario J - Trimmed Average Query using CLR aggregate--SELECT ProductID, dbo.TrimmedAvg_CLR(Cast(PercentPassed AS real)) ASAverageFROM TestAssignmentGROUP BY ProductIDORDER BY ProductID
--------------------------- Glossary --------------------------- Term | Definition ---------------------------
What I need to do is find all the letters that are at the beginning of the terms.
So if I have "apple" as a term, A is returned. Also, if I have "forest", "fruit", and "flower", F is returned, but only once. And if I have no terms that start with Q, Q is not returned. Lastly, if I have a term like " 'Walking' Pneumonia", it should recognize that the term starts with a W.
Hello!I want to get the first letter in a sql-query and compare with a QueryString.This is the pricip in ASP Classic:Select * From Dictionary Where Left(_Name, 1) = Request.Querystring["Letter"]I think you'll understand.Thanks.
I am using an OLEDB source to run a stored procedure, which returns records from a temp table. The destination table is exactly same as the temp table in the stored procedure. I've some collation settings on both the destination table and temp table, but both are exactly same.
I got Unicode to Non-unicode conversion error first. I dont know why it happened as there is no difference in source and destination table. I solved that issue using the data conversion component. Then I got the truncation error. I set the Ignore on Truncation on error output to get rid of that issue. Then the package executed without any problem. But all the nvarchar and varchar fields in the destination table got populated with only the first letter of data.
In my drop down menus - which are populated by tables - we can only use the scroll bar OR type in the first letter to find the item - Is there a way to type in several letters to find something? (e.g. if I want to find clockwork - right now I could type in "C" to get to the C's - but if I tried typing "clo" it would end up at the beginning of the "O's" - Thanks
SELECT name = SUBSTRING(name, 1, 1), total = COUNT(SUBSTRING(name, 1, 1)) FROM products GROUP BY SUBSTRING(name, 1, 1)
the assignment said that,
quote:"Do not display the letter and count unless at least three product names begin with the letter."
but i got the errors when I try following.
WHERE total >= 3
quote:Msg 207, Level 16, State 1, Line 4 Invalid column name 'total'.
WHERE COUNT(SUBSTRING(name, 1, 1)) >= 3
quote:Msg 147, Level 15, State 1, Line 1 An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
Hello. We have a list of 1000+ sku numbers. 90% of them start with u. I need to replace the u with T.
Concerns: It has to only replace the first letter, if there are other "u"s in the sku, they need to remain. Not all skus start with u, those that don't should remain the same.
I have searched and searched because I'm sure someone has requested the exact same thing but I can't find anything that is identical.
I have this so far but I know its not correct: set sku = replace(left(sku,1),'u',right(rtrim(sku),1)+ 'T')