2

i have a scalar valued function like this

CREATE FUNCTION getTotalWorkingSeconds(@machineList varchar(255))
RETURNS int
AS
BEGIN
  declare @res int
  Select @res =  Sum(DURATION) From PROCESSDATA where MACHINEID in (@machineList)
  return @res
END

i tried to use it like these

SELECT dbo.getTotalWorkingSeconds('3,2')

result; Conversion failed when converting the varchar value '3,2' to data type int.

--

SELECT dbo.getTotalWorkingSeconds(''''+'3,2'+'''')

result; Conversion failed when converting the varchar value ''3,2'' to data type int.

how i can pass id list to this function?

Edit: i can alter the function.

sddk
  • 1,115
  • 1
  • 10
  • 20
  • 2
    variables are interpreted as single monolithic values. To get your `3,2` string to be treated as two comma-separated integers, you'd have to build/execute the query statement dynamically. – Marc B Apr 13 '14 at 16:23
  • You will need to use [`Split Function`](http://stackoverflow.com/questions/697519/split-function-equivalent-in-tsql) inside your function to use these comma separated values. – M.Ali Apr 13 '14 at 16:52

1 Answers1

3

One solution is using xml parameter, so

CREATE FUNCTION Split
(
  @delimited nvarchar(max),
  @delimiter nvarchar(100)
) RETURNS @t TABLE
(
-- Id column can be commented out, not required for sql splitting string
  id int identity(1,1), -- I use this column for numbering splitted parts
  val nvarchar(max)
)
AS
BEGIN
  declare @xml xml
  set @xml = N'<root><r>' + replace(@delimited,@delimiter,'</r><r>') + '</r></root>'

  insert into @t(val)
  select
    r.value('.','varchar(max)') as item
  from @xml.nodes('//root/r') as records(r)

  RETURN
END
GO

CREATE FUNCTION getTotalWorkingSeconds(@machineList varchar(255))
RETURNS int
AS
BEGIN
  declare @t table (val nvarchar(100))
  insert into @t select * from dbo.split(@machineList,',')

  declare @res int
  Select @res =  Sum(DURATION) From PROCESSDATA where MACHINEID in (select val from @t)
  return @res
END
Reza
  • 18,865
  • 13
  • 88
  • 163
  • You cannot use `EXECUTE` inside a function. Also the way you are using OUTPUT param in your dynamic sql it would not. – M.Ali Apr 13 '14 at 16:49
  • 1
    this is a proper solution which will work for this problem :) + 1, Also have a look at this answer to see how you can use OUTPUT params with dynamic sql [`OUTPUT Parameters With Dynamic sql`](http://stackoverflow.com/questions/21812298/output-parameter-from-dynamic-sql) – M.Ali Apr 13 '14 at 17:00
  • i have adited line "insert into @t select * from dbo.split(@machineList,',')" like this "insert into @t select val from dbo.split(@machineList,',')" and it worked, thanks. – sddk Apr 13 '14 at 17:22