尝试创建函数时出现此错误:
'CREATE FUNCTION'必须是查询批处理中的第一个语句。
错误:
关键字'with'附近的语法不正确。
如果此语句是公用表表达式,则为xmlnamespaces 子句或更改跟踪上下文子句,前一个语句 必须以分号结束。必须声明标量变量 “@sep”。
这是我的T-SQL代码:
CREATE FUNCTION [dbo].[fn_Split] (@sep nvarchar(10), @s nvarchar(4000))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + (datalength(@sep)/2), CHARINDEX(@sep, @s, stop + (datalength(@sep)/2))
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 4000 END) AS value
FROM Pieces
)
;
答案 0 :(得分:1)
您没有在返回类型
中定义表结构create FUNCTION [dbo].[fn_Split] (@sep nvarchar(10), @s nvarchar(4000))
RETURNS table TABLE (pn varcahr(100), values varchar(8000))
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + (datalength(@sep)/2), CHARINDEX(@sep, @s, stop + (datalength(@sep)/2))
FROM Pieces
WHERE stop > 0
) SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 4000 END) AS value
FROM Pieces
)
;
答案 1 :(得分:0)
在USE AppName和创建语句之间添加GO
像
这样的东西Use AppName
GO
create FUNCTION [dbo].[fn_Split] (@sep nvarchar(10), @s nvarchar(4000))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + (datalength(@sep)/2), CHARINDEX(@sep, @s, stop + (datalength(@sep)/2))
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 4000 END) AS value
FROM Pieces
)
;
答案 2 :(得分:0)
better than you will use procedure :
CREATE procedure [dbo].[fn_Split]
@sep nvarchar(10),
@s nvarchar(4000))
AS
begin
your logic..
select col,.. from table;
end
答案 3 :(得分:0)
我得到了解决方案
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(query);
conn.Close();
现在我可以在SQL查询中使用Go语句运行...