[英]SQL SERVER sp_executesql incorrect syntax near ')'
當我嘗試在sql server 2014中執行sp_ExecuteSql時,我遇到了這個問題,那里有我的存儲過程:
alter proc search
@Name nvarchar
as
declare @SQL nvarchar
declare @Params nvarchar
begin
set @SQL = N' Select * from Table_1 , Table_2 where (1=1) '
if @Name is not null
begin
set @SQL = @SQL + ' and Table_2.thatoneID = ( Select Table_1.Id from Table_1 where Table_1.Name like ''%''+@Name+''%'' ) '
end
set @SQL = @SQL + ' and Table_2.thatoneID = Table_1.Id ; '
set @Params = '@Name nvarchar'
execute sp_executesql @SQL , @Params , @Name
end
當我想:
Execute search 'hh'
我收到了這個錯誤
Msg 102, Level 15, State 1, Line 29 Incorrect syntax near ')'.
您應該始終指定變量的長度,因此nvarchar(100)否則它將默認為1個字符。
只需通過打印來測試變量存儲的內容:
print @sql
print @params
沒有長度設置,唯一打印的是
@
為什么只有“@”而不是SELECT
關鍵字中的“S”,對於@sql
變量? 因為@sql
變量的開頭有一個空格。
與為每個變量設置大小相反(我只是選擇max,因為我不知道你實際需要的長度):
declare @SQL nvarchar(max)
, @Name nvarchar(max)
declare @Params nvarchar(max)
begin
set @SQL = N' Select * from Table_1 , Table_2 where (1=1) '
if @Name is not null
begin
set @SQL = @SQL + ' and Table_2.thatoneID = ( Select Table_1.Id from Table_1 where Table_1.Name like ''%''+@Name+''%'' ) '
end
set @SQL = @SQL + ' and Table_2.thatoneID = Table_1.Id ; '
set @Params = '@Name nvarchar'
print @sql
print @params
end
哪個會給你:
Select * from Table_1 , Table_2 where (1=1) and Table_2.thatoneID = Table_1.Id ;
@Name nvarchar
我建議你先嘗試一下,看看你是否仍然得到錯誤。
首先 - 請使用表別名 。
其次,重寫您的查詢,您使用舊的ANSI樣式 。
第三 - 定義nvarchar
大小。
第四 - 為什么你甚至使用動態SQL?
ALTER PROC search
@Name nvarchar(max)
AS
SELECT *
FROM Table_1 t1
INNER JOIN Table_2 t2
ON t2.thatoneID = t1.Id
WHERE (1=1) AND t1.Name LIKE '%'+@Name+'%'
如果您堅持使用動態SQL,可以使用:
ALTER PROC search
@Name nvarchar(max)
AS
DECLARE @SQL nvarchar(max),
@Params nvarchar(max)
SELECT @SQL = N'
SELECT *
FROM Table_1 t1
INNER JOIN Table_2 t2
ON t2.thatoneID = t1.Id
WHERE (1=1) AND t1.Name LIKE ''%''+@Name+''%'''
PRINT @sql
SET @Params = '@Name nvarchar(max)'
EXEC sp_executesql @SQL, @Params, @Name = @Name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.