create a TableAdapter method with parameters when using OLEDB
October 2, 2009
If use the following query script for creating a TableAdapter method, like “GetDataById”, when using OLEDB:
“SELECT * FROM aTable WHERE theID=@id”
an error will happen:
“error in where clause near ‘@’ unable to parse query text”
The solution is to use “?”, instead of “@variablename”, so teh following will succeed:
“SELECT * FROM aTable WHERE theID=?”
combine multiple rows in one
September 3, 2009
I have a table as:
itemID tagID
100 111
200 222
200 223
300 333
300 334
300 335
I want to have a select statement to group records by itemID and one itemID will have only one row, multiple tagIDs will be combined in one field.
Step1: create a scalar-valued function (UDF)
ALTER FUNCTION sUDF_itemTagIds(@aItemId int)
RETURNS varchar(MAX)
AS
BEGIN
DECLARE @tagids varchar(max)
SELECT @tagids = COALESCE(@tagids + ‘,’,”) + convert(varchar(20),tagID)
FROM myTable
WHERE itemID = @aItemId
RETURN @tagids
END
GO
Step2: call the UDF from the SQL script:
SELECT itemID,dbo.sUDF_itemTagIds(itemID) as tagIDs
FROM myTable
GROUP BY itemID
Here is the result:
itemID tagIDs
100 111
200 222,223
300 333,334,335
Intro to User Defined Functions
The ability to create a user-defined function (UDF) is a new feature added to SQL Server 2000.
A user-defined function is a database object that encapsulates one or more Transact-SQL statements for reuse. This definition is similar to the one for stored procedures, but there are many important differences between user-defined functions and stored procedures—the most pronounced being what types of data they can return.
Scalar Functions
A scalar function returns a single value of the data type referenced in the RETURNS clause of the CREATE FUNCTION statement. The returned data can be of any type except text, ntext, image, cursor, or timestamp.
Inline Table-Valued Functions
An inline table-valued function returns a variable of data type table whose value is derived from a single SELECT statement.
Multi-Statement Table-Valued Functions
The multi-statement table-valued function is slightly more complicated than the other two types of functions because it uses multiple statements to build the table that is returned to the calling statement. Unlike the inline table-valued function, a table variable must be explicitly declared and defined.
Returns the first nonnull expression among its arguments.
Syntax
COALESCE ( expression [ ,...n ] )
