Incorrect syntax near '.' - sql

I am trying to run a stored procedure in SQL Server 2008. After I created the procedure, I selected the option to "Script Table AS EXECUTE", which (after entering the SELECT queries for the field names) comes up as:
DECLARE #RC int
DECLARE #tablename varchar(50)
DECLARE #field1 varchar(25)
DECLARE #field2 varchar(25)
SELECT #tablename = '[databasename].[dbo].[tablename]'
SELECT #field1 = 'name'
SELECT #field2 = 'amount'
EXECUTE #RC = [databasename].[dbo].[procedurename]
#tablename
,#field1
,#field2
GO
I then get the following error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'
but there doesn't appear to be any '.' anywhere near line 1 or anywhere other than the table names?

Nothing is wrong with that code. As it stated in the comment that something is wrong with your stored procedure. Take the source code of the procedure, delete lines with create/alter and the input parameters until the first begin. After that remove the last END. Replace all the parameters in the code and execute it as normal TSQL statement. In that case you'll easily find where it is failing.
Just to be sure that your code is working, execute following script:
CREATE PROCEDURE [procedurename]
#tablename VARCHAR(1000)
,#field1 VARCHAR(1000)
,#field2 VARCHAR(1000)
AS
BEGIN
SELECT 1
END
GO
DECLARE #RC int
DECLARE #tablename varchar(50)
DECLARE #field1 varchar(25)
DECLARE #field2 varchar(25)
SELECT #tablename = '[databasename].[dbo].[tablename]'
SELECT #field1 = 'name'
SELECT #field2 = 'amount'
EXECUTE #RC = [dbo].[procedurename]
#tablename
,#field1
,#field2
GO
DROP PROCEDURE [procedurename]
GO

Related

Sql OpenJson - Incorrect syntax near '$.recordtype'

I have a stored procedure which i'm going to execute and the function of this is it will insert the json result in my table "ItemTransaction". Then i'm going to retrieve it by declaring variable which the JsonString. the problem is i cannot execute my stored procedure.
Incorrect syntax near '$.recordtype'.
I don't know which exactly the error.
exec AWSLINK.APILINK.dbo.spu_JsonSendData 'LoadItem',#pBranchCode,#pTranNo,'','','Test','POST'
Declare #JsonString varchar(MAX) = (Select DataReceived from AWSLINK.APILINK.dbo.ItemTransaction where
DocType ='LoadItem' and BranchCode = #pBranchCode and TranNo = #pTranNo)
SELECT * FROM
OPENJSON ( #JsonString,'$."records"')
WITH (
RecordType varchar(200) '$.recordtype' ,
ItemID varchar '$.id',
ItemDetails varchar(200) '$.itemid',
Quantity int '$.locationquantityonhand'
)
Something like this
drop proc if exists dbo.TestExample;
go
create proc dbo.TestExample
#var1 int,
#json nvarchar(max) output
as
set nocount on;
select #json=(select #var1 var1 for json path, without_array_wrapper);
go
declare
#out_json nvarchar(max);
exec dbo.TestExample 1, #json=#out_json output;
print (#out_json);
Output:
{"var1":1}

Insert procedure with 2 string parameters

I wrote this procedure to insert 2 string variables into a table:
ALTER Procedure
[dbo].[IND] (#VAssetID varchar(50), #UAssetID nvarchar(255))
As
BEGIN
Declare #Query1 as varchar(max)
Set #Query1 =
'Insert into IndMatch(V_AssetID,U_AssetID) values('+ #VAssetID +','+#UAssetID+')'
EXECUTE(#Query1)
END
When I run the procedure with number strings only it works fine as soon as I try and insert alphanumeric codes the procedure fails.
When the procedure executes with numbers strings only:
Exec IND #VAssetID = '231243332', #UAssetID = '21343321'
The procedure executes fine with and inserts the values into the table.
When the procedure executes with alphanumeric strings:
Exec IND #VAssetID = '2312I43332', #UAssetID = '21T343R321'
It generates the error:
Incorrect syntax near 'I43332'.
Please assist
Why execute as a string? This'll work just fine:
ALTER Procedure [dbo].[IND] (#VAssetID varchar(50), #UAssetID nvarchar(255))
As
BEGIN
Insert into IndMatch(V_AssetID,U_AssetID) values(#VAssetID, #UAssetID)
END
you are missing the [ ' ] around the values.
It will try to execute an insert like so:
Insert into IndMatch(V_AssetID,U_AssetID) values(2312I43332,21T343R321 )
but the correct syntax should be
Insert into IndMatch(V_AssetID,U_AssetID) values('2312I43332','21T343R321' )
you need to do this:
ALTER Procedure
[dbo].[IND] (#VAssetID varchar(50), #UAssetID nvarchar(255))
As
BEGIN
Declare #Query1 as varchar(max)
Set #Query1 =
'Insert into IndMatch(V_AssetID,U_AssetID) values('''+ #VAssetID +''','''+#UAssetID+''')'
EXECUTE(#Query1)
END
Run this and this should explain it:
DECLARE #Query1 VARCHAR(MAX), #VAssetID VARCHAR(50), #UAssetID NVARCHAR(255);
SET #VAssetID = '231243332';
SET #UAssetID = '21343321';
SET #Query1 = 'Insert into IndMatch(V_AssetID,U_AssetID) values('+#VAssetID+','+#UAssetID+')';
PRINT #Query1;
SET #Query1 = 'Insert into IndMatch(V_AssetID,U_AssetID) values('''+#VAssetID+''','''+#UAssetID+''')';
PRINT #Query1;
PRINT RESULT:
Better yet you can do this as I don't see a need for dynamic sql here:
ALTER Procedure
[dbo].[IND] (#VAssetID varchar(50), #UAssetID nvarchar(255))
As
BEGIN
Insert into IndMatch(V_AssetID,U_AssetID) values( #VAssetID , #UAssetID )
END

Getting an error when passing the table name as parameter to a function

I am new to SQL query and here I am trying to get the complete name from dbo.Customer_List table and have written this code. However when try to run am getting the following error. I don't know what I am doing wrong.
Error message is:
Msg 1087, Level 16, State 1, Procedure getFullName, Line 11
Must declare the table variable "#tblName".
Msg 1087, Level 16, State 1, Procedure getFullName, Line 14
Must declare the table variable "#tblName".
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'Last_Name'.
Code is:
IF OBJECT_ID (N'dbo.getFullName', N'FN') IS NOT NULL
DROP FUNCTION getFullName
GO
Create function dbo.getFullName(#tblName varchar(30),#fstName varchar(50), #lstName varchar(50) ) returns varchar(101)
As
Begin
Declare #rowCount int
Declare #rowIteration int
Declare #temp varchar(101)
Select #rowCount = count(*) from #tblName
Set #rowIteration = 1
While ( #rowIteration <= #rowCount)
Select #temp = #fstName+' '+#lstName from #tblName where #tblName.Customer_Id = #rowIteration
Begin
Set #rowIteration = #rowIteration + 1
End
return #temp
End
Go
Declare #tblName varchar(30),#fstName varchar(50), #lstName varchar(50)
set #tblName = convert(varchar(30),'dbo.Customer_List')
set #fstName = convert(varchar(50),'dbo.Customer_List.First_Name')
set #lstName = convert(varchar(50),'dbo.Customer_List.Last_Name')
Execute ('select dbo.getFullName('+ #tblName+','+ #fstName+','+ #lstName )
You are essentially trying to perform dynamic sql here without performing it properly. You can't just pass in a variable as a table name, that's why you're getting your error.
You need to recreate this as a stored procedure (or at least you will in sql-server which does not like DML transactions in functions) and use the following dynamic sql:
Declare #sql nvarchar(100)
Set #sql = 'Set #int = (Select count(*) from ' + #tblName + ')'
execute sp_executesql #sql, N'#int int output', #int = #rowCount output

Stored Procedure to import data into SQL Server database... Error

I have a text file file1.txt in the below format. Column 1 is AGUSR1 & Column 2 is AGUSR2. There are 3 records in the file:
"AGUSR1"|"AGUSR2"
"JASON "|"DEBBIE "
"JOY "|"JASON "
"ANNA "|"JOHN "
I have written a stored procedure to upload this text file into a SQL Server database like this:
CREATE PROCEDURE sp_Import
#TableName varchar(200),
#FilePath varchar(200)
AS
DECLARE #SQL varchar(5000)
SET #SQL = 'BULK INSERT ' + #TableName + ' FROM ''' + #FilePath +
''' WITH (FIELDTERMINATOR = ''|'', ROWTERMINATOR = ''{CR}{LF}'')'
EXEC (#SQL)
To execute it, I have used this statement:
EXEC sp_Import '[DB_DEMO].[dbo].[file1]' , '\\kacl1tsp048\DEMO\file1.txt'
Note : kacl1tsp048 is a remote server the input text file is at.
On execution, I am getting the below error -
Msg 4863, Level 16, State 1, Line 1
Bulk load data conversion error (truncation) for row 1, column 2 (AGUSR2).
The import into table schema is
CREATE TABLE [dbo].[file1]
(
[AGUSR1] [varchar](10) NULL,
[AGUSR2] [varchar](10) NULL
)
For ad-hoc style data imports I sometimes dispense with using BULK INSERTS in favor of selecting from the file itself to then process it. You could do something similar by creating a procedure to read your file as a table:
CREATE FUNCTION [dbo].[uftReadfileAsTable]
(
#Path VARCHAR(255),
#Filename VARCHAR(100)
)
RETURNS
#File TABLE
(
[LineNo] int identity(1,1),
line varchar(8000))
AS
BEGIN
DECLARE #objFileSystem int
,#objTextStream int,
#objErrorObject int,
#strErrorMessage Varchar(1000),
#Command varchar(1000),
#hr int,
#String VARCHAR(8000),
#YesOrNo INT
select #strErrorMessage='opening the File System Object'
EXECUTE #hr = sp_OACreate 'Scripting.FileSystemObject' , #objFileSystem OUT
if #HR=0 Select #objErrorObject=#objFileSystem, #strErrorMessage='Opening file "'+#path+'\'+#filename+'"',#command=#path+'\'+#filename
if #HR=0 execute #hr = sp_OAMethod #objFileSystem , 'OpenTextFile'
, #objTextStream OUT, #command,1,false,0--for reading, FormatASCII
WHILE #hr=0
BEGIN
if #HR=0 Select #objErrorObject=#objTextStream,
#strErrorMessage='finding out if there is more to read in "'+#filename+'"'
if #HR=0 execute #hr = sp_OAGetProperty #objTextStream, 'AtEndOfStream', #YesOrNo OUTPUT
IF #YesOrNo<>0 break
if #HR=0 Select #objErrorObject=#objTextStream,
#strErrorMessage='reading from the output file "'+#filename+'"'
if #HR=0 execute #hr = sp_OAMethod #objTextStream, 'Readline', #String OUTPUT
INSERT INTO #file(line) SELECT #String
END
if #HR=0 Select #objErrorObject=#objTextStream,
#strErrorMessage='closing the output file "'+#filename+'"'
if #HR=0 execute #hr = sp_OAMethod #objTextStream, 'Close'
if #hr<>0
begin
Declare
#Source varchar(255),
#Description Varchar(255),
#Helpfile Varchar(255),
#HelpID int
EXECUTE sp_OAGetErrorInfo #objErrorObject,
#source output,#Description output,#Helpfile output,#HelpID output
Select #strErrorMessage='Error whilst '
+coalesce(#strErrorMessage,'doing something')
+', '+coalesce(#Description,'')
insert into #File(line) select #strErrorMessage
end
EXECUTE sp_OADestroy #objTextStream
-- Fill the table variable with the rows for your result set
RETURN
END
Now you have a proc to convert your file to a table. You would still have to deal with the formatting of your delimiters so you could run something like this to populate [dbo].[file1]:
;WITH Split_Names (Value,Name, xmlname)
AS
(
SELECT
[LineNo],
line,
CONVERT(XML,'<Lines><line>'
+ REPLACE(line,'"|"', '</line><line>') + '</line></Lines>') AS xmlname
from [dbo].[uftReadfileAsTable]('\\kacl1tsp048\DEMO\file1.txt')
where line not like '"AGUSR1"%'
)
SELECT
Value,
RTRIM(REPLACE(xmlname.value('/Lines[1]/line[1]','varchar(100)'),'"', '')) AS AGUSR1,
RTRIM(REPLACE(xmlname.value('/Lines[1]/line[2]','varchar(100)'),'"', '')) AS AGUSR2
INTO [dbo].[file1]
FROM Split_Names
Hope that helps a little?!

Pass a TABLE variable to sp_executesql

I'm trying to pass a TABLE variable to the sp_executesql procedure:
DECLARE #params NVARCHAR(MAX)
SET #params = '#workingData TABLE ( col1 VARCHAR(20),
col2 VARCHAR(50) )'
EXEC sp_executesql #sql, #params, #workingData
I get the error:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'TABLE'.
I tried omitting the column specification after 'TABLE'. I also tried to declare the table as a variable inside the dynamic SQL. But no luck...
Seems to me that TABLE variables aren't allowed to be passed as parameters in this procedure?. BTW: I'm running MSSQL2008 R2.
I'm not interested in using a local temp table like #workingData because I load the working data from another procedure:
INSERT INTO #workingData
EXEC myProc #param1, #param2
Which I cannot do directly into a temp varaible (right?)...
Any help appreciated!
If you are using SQL Server 2008, to pass a table variable to a stored procedure you must first define the table type, e.g.:
CREATE TYPE SalesHistoryTableType AS TABLE
(
[Product] [varchar](10) NULL,
[SaleDate] [datetime] NULL,
[SalePrice] [money] NULL
)
GO
or use an existing table type stored in the database.
Use this query to locate existing table types
SELECT * FROM sys.table_types
To use in an stored procedure, declare an input variable to be the table:
CREATE PROCEDURE usp_myproc
(
#TableVariable SalesHistoryTableType READONLY
)
AS BEGIN
--Do stuff
END
GO
Populate the table variable before passing to the stored procedure:
DECLARE #DataTable AS SalesHistoryTableType
INSERT INTO #DataTable
SELECT * FROM (Some data)
Call the stored procedure:
EXECUTE usp_myproc
#TableVariable = #DataTable
Further discussions here.
OK, this will get me what I want, but surely isn't pretty:
DECLARE #workingData TABLE ( col1 VARCHAR(20),
col2 VARCHAR(20) )
INSERT INTO #workingData
EXEC myProc
/* Unfortunately table variables are outside scope
for the dynamic SQL later run. We copy the
table to a temp table.
The table variable is needed to extract data directly
from the strored procedure call above...
*/
SELECT *
INTO #workingData
FROM #workingData
DECLARE #sql NVARCHAR(MAX)
SET #sql = 'SELECT * FROM #workingData'
EXEC sp_executesql #sql
There must be a better way to pass this temporary resultset into sp_executesql!?
Regards
Alex
While this may not directly answer your question, it should solve your issue overall.
You can indeed capture the results of a Stored Procedure execution into a temporary table:
INSERT INTO #workingData
EXEC myProc
So change your code to look like the following:
CREATE TABLE #workingData ( col1 VARCHAR(20),
col2 VARCHAR(20) )
INSERT INTO #workingData
EXEC myProc
DECLARE #sql NVARCHAR(MAX)
SET #sql = 'SELECT * FROM #workingData'
EXEC sp_executesql #sql
Regards,
Tim
Alter PROCEDURE sp_table_getcount
#tblname nvarchar(50) ,
#totalrow int output
AS
BEGIN
Declare #params nvarchar(1000)
Declare #sql nvarchar(1000)
set #sql = N'Select #cnt= count(*) From #tbl'
set #params = N'#tbl nvarchar(50) , #cnt int OUTPUT'
Exec sp_executesql #sql , #params ,#tbl=#tblname , #cnt = #totalrow OUTPUT
END
GO
Please note that the above code will not work as table as a object is out of the scope.It will give you the error: must declare table variable.In order to work around we can do the following.
Alter PROCEDURE sp_table_getcount
#tblname nvarchar(50) ,
#totalrow int output
AS
BEGIN
Declare #params nvarchar(1000)
Declare #sql nvarchar(1000)
set #sql = N'Select #cnt= count(*) From dbo.' + #tblname
set #params = N'#cnt int OUTPUT'
Exec sp_executesql #sql , #params , #cnt = #totalrow OUTPUT
END
GO
So-called TableType is tricky. #Alex version should work. However, to simplify and faster performance, go check sys.tables for matching table name while not compromise security and performance.
Here it is
create proc [dbo].Test11
#t1 AS nvarchar(250), #t2 nvarchar(250)
AS
BEGIN
SET nocount ON;
DECLARE #query AS nvarchar(MAX)
if exists (select * from sys.tables where name = #t1) and
exists (select * from sys.tables where name = #t2)
begin
SET #query = N'select * FROM '+ #t1 + N' join ' + #t2 + N' ON ...' ;
select 'Safe and fast'
print #query
exec sp_executesql #query
end
else
select 'Bad, no way Jose.'
SET nocount OFF;
END
GO