I'm using the following code:
This is Update code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UpdateDataTable]
(#TABLEID BIGINT,
#QUERY NVARCHAR(MAX),
#DATAOBJECT NVARCHAR(MAX))
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
BEGIN TRANSACTION TX1
-- DECLARATIONS
--DECLARE #DTABLE NVARCHAR(MAX) = 'DYNAMIC_Order_C905AE71028F4B0094B94EDAD0026CE2'
DECLARE #DTABLE NVARCHAR(MAX) = (SELECT DynamicTableId FROM TABLES WHERE Id=#TABLEID)
--DECLARE #QUERY NVARCHAR(MAX)='qty=4356'
--DECLARE #DATAOBJECT NVARCHAR(MAX)='{"product":"iPad 2018 pro", "amount":260000}'
-- BUILDING QUERY
DECLARE #QUERYSQL NVARCHAR(MAX) = 'SELECT Id AS TableId FROM '+#DTABLE+' WHERE '+#QUERY
-- RETRIEVING IDS OF UPDATING ROWS
DECLARE #UPDATING_IDS_TEMP TABLE(TableId BIGINT)
INSERT INTO #UPDATING_IDS_TEMP
EXEC sys.sp_executesql #QUERYSQL
DROP TABLE IF EXISTS #UPDATING_IDS
SELECT ROW_NUMBER() OVER (ORDER BY TableId)-1 AS Id, TableId
INTO #UPDATING_IDS
FROM #UPDATING_IDS_TEMP
-- UPDATING ROWS
DECLARE #INDEX BIGINT = 0
DECLARE #MAX BIGINT = (SELECT COUNT(*) FROM #UPDATING_IDS)
WHILE(#INDEX < #MAX)
BEGIN
--DECLARE #ROWID BIGINT = (SELECT TableId FROM #UPDATING_IDS WHERE Id=#INDEX)
DECLARE #ROWID BIGINT = 'N'''+ (SELECT TableId FROM #UPDATING_IDS WHERE Id=#INDEX) +''','
--SELECT #ROWID
EXEC FN_UpdateFieldByJson #DTABLE, #ROWID, #DATAOBJECT
SET #INDEX = #INDEX + 1
END
SELECT 'Completed'
COMMIT TRANSACTION T1
END
This is Insert Code
/****** Object: StoredProcedure [dbo].[InsertDataToTable] Script Date: 2/7/2020 1:57:07 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[InsertDataToTable](#tableId BIGINT, #data NVARCHAR(MAX))
AS
BEGIN
--DECLARE #tableId BIGINT = 10
--DECLARE #data NVARCHAR(MAX) = '{"artist":"usher","song name":"test songs"}'
DECLARE #dynamicTableId NVARCHAR(MAX) = (SELECT dynamicTableId FROM Tables WHERE Id=#tableId)
DECLARE #insertSql NVARCHAR(MAX)='INSERT INTO '+#dynamicTableId+'('
DECLARE #keyList NVARCHAR(MAX)=''
DECLARE #valueList NVARCHAR(MAX)=''
DROP TABLE IF EXISTS #FIELDS
SELECT ROW_NUMBER() OVER (ORDER BY [KEY])-1 AS Id,* INTO #FIELDS FROM OPENJSON(#data)
DECLARE #fieldCount BIGINT = (SELECT COUNT(*) FROM #FIELDS)
DECLARE #index BIGINT=0
WHILE ( #index < #fieldCount)
BEGIN
SET #keyList = #keyList+'['+(SELECT [KEY] FROM #FIELDS WHERE Id=#index)+'],'
-- ADDING WITHOUT QUOTES IF IT'S A NUMBER
IF ( (SELECT [TYPE] FROM #FIELDS WHERE Id=#index) = 2 )
BEGIN
SET #valueList = #valueList+''+dbo.ZenEncToChar((SELECT [VALUE] FROM #FIELDS WHERE Id=#index))+','
END
ELSE
BEGIN
SET #valueList = #valueList+'N'''+dbo.ZenEncToChar((SELECT [VALUE] FROM #FIELDS WHERE Id=#index))+''','
END
SET #index = #index+1
END
SET #keyList=SUBSTRING(#keyList,1, LEN(#keyList)-1)
SET #valueList=SUBSTRING(#valueList,1, LEN(#valueList)-1)
SET #insertSql = #insertSql + #keyList+') VALUES('+#valueList+')'
--SELECT #insertSql
EXEC sys.sp_executesql #insertSql
--SELECT ROW_NUMBER() OVER (ORDER BY COLUMN_NAME)-1 AS Id,COLUMN_NAME
--FROM INFORMATION_SCHEMA.COLUMNS
--WHERE TABLE_NAME = #dynamicTableId
END
User cannot insert/update ' symbol as table input in tables. So in here my insert table is working perfectly but update is not working. So please help me
How do I update unicode text from the SQL Server Management Studio query window?
Related
I am trying to run a Stored Procedure that Inserts into a Table.
I keep getting the Incorrect syntax near 'tbl_1_2'.
It doesn't Insert the data.I am using MSSQL2012
Alter PROCEDURE [dbo].[TT] AS
BEGIN
declare #tbl varchar(100);
set #tbl='tbl_1_2';
declare #sql varchar(100);
DECLARE #ptablename VARCHAR(max) = (#tbl)
set #ptablename=#tbl
SET #sql = 'INSERT INTO ' + #ptablename ;
EXEC (#sql)
select *
from (
values('1','2')
) t1 (c1, c2)
End
See this sample and compare with your code to understand your error.
Create Table Test (ID int, Name sysname)
Go
Declare #TableName sysname = 'Test'
DECLARE #ID int = 1
DECLARE #Name sysname = 'Meysam'
Declare #SQL nVarchar(4000) = 'INSERT #TableName (ID, Name) Values (#ID, N''#Name'')'
Set #SQL = REPLACE(#SQL, '#TableName', #TableName)
Set #SQL = REPLACE(#SQL, '#ID', #ID)
Set #SQL = REPLACE(#SQL, '#Name', #Name)
EXEC (#SQL)
SELECT * FROM Test
Is it possible to print the Dynamic select statement after passing the parameters values.When i print the SELECT #SQL.It is giving only select statement without parameter values.In my below procedure the dynamic select statement not giving correct output after passing the parameters.But when i directly passing the the parameter values into the select statement it is giving correct output.In my below procedure splitting function is working fine.Else part in
if statement is not working properly.
CREATE TYPE TableVariable AS TABLE
(
id int identity(1,1),
field_ids INT,
value VARCHAR(MAX)
)
Alter PROCEDURE Testing
(
#TableVar TableVariable READONLY,
#Catalog_id INT
)
AS
Declare #maxPK INT
Declare #pk INT
Declare #fid INT
Declare #is_List SMALLINT
Declare #val VARCHAR(MAX)
Declare #field_Type VARCHAR(50)
Declare #Where VARCHAR(MAX)
Declare #SQL NVARCHAR(MAX);
Set #pk = 1
BEGIN
BEGIN TRY
SET NOCOUNT ON;
Select #maxPK = count(*) From #TableVar
SELECT #Catalog_id
Set #SQL = 'SELECT DISTINCT v1.entity_id from values v1 inner join listings l ON v1.entity_id = l.entity_id WHERE l.c_id=#Catalog_id'
While #pk <= #maxPK
BEGIN
SELECT #fid= field_ids FROM #TableVar where id=#pk;
SELECT #val= value FROM #TableVar where id=#pk;
SELECT #field_Type=type,#is_List=is_list FROM FIELD WHERE ID=#fid
IF (#is_List = 0)
BEGIN
SET #SQL += ' and exists (select 1 from values v'+convert(varchar(15),#pk+1)+' where v1.entity_id = v'+convert(varchar(15),#pk+1)+'.entity_id and v'+convert(varchar(15),#pk+1)+'.field_id=#fid and(value IN(SELECT val FROM spliting(#val,'',''))))'
SELECT #fid
END
else IF (#is_List = 1 OR #field_Type = 'xy')
BEGIN
SET #SQL += ' and exists (select 1 from values v'+convert(varchar(15),#pk+1)+' where v1.entity_id = v'+convert(varchar(15),#pk+1)+'.entity_id and v'+convert(varchar(15),#pk+1)+'.field_id=#fid and(value in(#val)))'
SELECT #fid
END
Select #pk = #pk + 1
END
EXECUTE SP_EXECUTESQL #SQL, N'#Catalog_id int,#fid int,#val varchar(max)',#Catalog_id=#Catalog_id,#fid=#fid,#val=#val
SELECT #SQL
END TRY
BEGIN CATCH
END CATCH
END
DECLARE #DepartmentTVP AS TableVariable;
insert into #DepartmentTVP values(1780,'Smooth As Silk Deep Moisture Shampoo,Smooth As Silk Deeper Moisture Conditioner')
--insert into #DepartmentTVP values(1780,'Smooth As Silk Deeper Moisture Conditioner')
insert into #DepartmentTVP values(1782,'037-05-1129')
insert into #DepartmentTVP values(2320,'["fairtrade","usda_organic","non_gmo_verified"]')
SELECT * FROM #DepartmentTVP
EXEC Testing #DepartmentTVP,583
Yes right before the statment:
EXECUTE SP_EXECUTESQL #SQL, N'#Catalog_id int,#fid int,#val varchar(max)',#Catalog_id=#Catalog_id,#fid=#fid,#val=#val
type:
print #SQL
I have a stored procedure which uses cursor. I want to know any equivalent set base query for the cursor.
USE [T04_676]
GO
/****** Object: StoredProcedure [dbo].[proc_InsertAssessmentCast] Script Date: 3/16/2016 7:43:44 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Capgemini>
-- Create date: <12-Mar-2016>
-- Description: <This Stored procedure is used to create table 'assessment_cast' and fill data into it>
-- exec proc_InsertAssessmentCast
-- =============================================
CREATE PROCEDURE [dbo].[proc_InsertAssessmentCast]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #tmpTableNames TABLE
(
TableName varchar(250),
PatientID_ITM_ID INT,
date_ITM_ID INT,
KVSTableType INT,
Association_ITM_ID INT
)
DECLARE #tmpAssociatedColumn_ITM_ID TABLE
(
InitialTableMasterID INT
)
DECLARE #AssociatedColumn_ITM_ID INT
DECLARE #AssociatedColumn_ITM_ID_List VARCHAR(400)
DECLARE #TableName varchar(250)
DECLARE #PatientID_ITM_ID INT
DECLARE #date_ITM_ID INT
DECLARE #KVSTableType INT
DECLARE #Association_ITM_ID INT
DECLARE #SameRowID INT
DECLARE #T04PKID INT
DECLARE #T04CMID INT
DECLARE #T04Value VARCHAR(250)
DECLARE #sqlT04Value nvarchar(MAX)
DECLARE #tmpValue TABLE
(
Value varchar(250)
)
CREATE TABLE #tmpAssessmentRows
(
PrimaryKeyTableID INT,
ColumnID INT,
Value varchar(250)
)
DECLARE #sqlSameRowID NVARCHAR(250),#sqlT04_Value_Query NVARCHAR(MAX)
DECLARE #ColWithAliasTbl TABLE (colID int,colName varchar(50) )
DECLARE #PivotTBL VARCHAR(MAX)=''
DECLARE #ColID VARCHAR(MAX)
DECLARE #ChkPtntID VARCHAR(MAX)
DECLARE #ColName VARCHAR(MAX)
DECLARE #AllColID VARCHAR(MAX) = ''
DECLARE #AllColName VARCHAR(MAX) = ''
BEGIN TRY
IF EXISTS (SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tmpAssesessment_Cast]') AND type in (N'U'))
BEGIN
DROP TABLE tmpAssesessment_Cast
END
IF EXISTS (SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[assessment_cast]') AND type in (N'U'))
BEGIN
DROP TABLE assessment_cast
END
IF NOT EXISTS (SELECT name FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[InitialOriginalDataKVS]') AND name = N'ix_InitialOriginalDataKVS_SameRowID')
CREATE NONCLUSTERED INDEX [ix_InitialOriginalDataKVS_SameRowID] ON [dbo].[InitialOriginalDataKVS]
(
[InitialTableMasterID] ASC
)
INCLUDE ( [SameRowID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
--Insert Table names of tables having both columns: patientID and date
INSERT INTO #tmpTableNames
SELECT ITM1.TableName,ITM1.InitialTableMasterID,ITM2.InitialTableMasterID,ITM1.KVSTableType,0 AS Association_ITM_ID
FROM InitialTableMaster ITM1
INNER JOIN InitialTableMaster ITM2 ON ITM1.TableName=ITM2.TableName
WHERE ITM1.ColumnName ='patientID' AND ITM2.ColumnName ='date'
--Set Association for the column in table
UPDATE #tmpTableNames
SET Association_ITM_ID=Association
FROM InitialTableMaster ITM
INNER JOIN #tmpTableNames tmpTableNames ON tmpTableNames.TableName=ITM.TableName
WHERE Association <> 0 AND tmpTableNames.KVSTableType=1
--Do not consider tables with KVSTableType=1 having no Association
DELETE FROM #tmpTableNames
WHERE KVSTableType=1 AND Association_ITM_ID=0
SELECT TOP 1
#PatientID_ITM_ID=PatientID_ITM_ID,
#date_ITM_ID=date_ITM_ID,
#Association_ITM_ID=Association_ITM_ID
FROM #tmpTableNames
----Logic to get the associated columns ID values in list
INSERT INTO #tmpAssociatedColumn_ITM_ID
SELECT InitialTableMasterID
FROM InitialTableMaster
WHERE Association=#Association_ITM_ID and InitialTableMasterID <>#Association_ITM_ID
WHILE ((SELECT COUNT(1) FROM #tmpAssociatedColumn_ITM_ID)>0)
BEGIN
SELECT TOP 1 #AssociatedColumn_ITM_ID=InitialTableMasterID
FROM #tmpAssociatedColumn_ITM_ID
SET #AssociatedColumn_ITM_ID_List= ISNULL(#AssociatedColumn_ITM_ID_List,'') + '['+ CONVERT(NVARCHAR,#AssociatedColumn_ITM_ID) + '],'
DELETE FROM #tmpAssociatedColumn_ITM_ID
WHERE InitialTableMasterID=#AssociatedColumn_ITM_ID
END
SET #AssociatedColumn_ITM_ID_List=SUBSTRING(#AssociatedColumn_ITM_ID_List,0,LEN(#AssociatedColumn_ITM_ID_List))
print '1'
print #AssociatedColumn_ITM_ID_List
SET #sqlT04Value='
SELECT COALESCE('+ #AssociatedColumn_ITM_ID_List + ') as ''Value''
FROM [InitialOriginalDataKVS]
PIVOT(max(Value)
FOR InitialTableMasterID IN ('+ #AssociatedColumn_ITM_ID_List +')) AS PVTTable
WHERE SameRowID = '
--DECLARE GetSameRowIDs CURSOR STATIC LOCAL FOR
DECLARE GetSameRowIDs CURSOR FORWARD_ONLY READ_ONLY FAST_FORWARD FOR
SELECT sameRowID FROM InitialOriginalDataKVS
WHERE InitialTableMasterID=#PatientID_ITM_ID AND NewFlag=1
GROUP BY sameRowID
OPEN GetSameRowIDs
FETCH NEXT FROM GetSameRowIDs
INTO #SameRowID
WHILE (##FETCH_STATUS = 0) -- Inner cursor loop
BEGIN
SET #T04PKID=0
SELECT #T04PKID=PrimaryKeyTableID
FROM dbo.PrimaryKeyForPredicting
WHERE PatientID IN (SELECT value FROM dbo.InitialOriginalDataKVS
WHERE SameRowID=#SameRowID AND InitialTableMasterID=#PatientID_ITM_ID)
AND [date] IN (SELECT value FROM dbo.InitialOriginalDataKVS
WHERE SameRowID=#SameRowID AND InitialTableMasterID=#date_ITM_ID)
--Process only if the combination of patientID and date exists in 'PrimaryKeyForPredicting'
IF(ISNULL(#T04PKID,0)<> 0)
BEGIN
DELETE FROM #tmpValue
SET #T04Value=NULL
SET #sqlSameRowID=CONVERT(VARCHAR(50),#SameRowID)
SET #sqlT04_Value_Query=#sqlT04Value+#sqlSameRowID
INSERT INTO #tmpValue
EXEC sp_executesql #sqlT04_Value_Query
IF((SELECT COUNT(1) FROM #tmpValue)>0)
BEGIN
SELECT #T04Value=Value FROM #tmpValue
END
SELECT #T04CMID = ColumnID
FROM [dbo].[PrimaryKeyForModeling]
WHERE ColumnName IN (SELECT value FROM [InitialOriginalDataKVS]
WHERE SameRowID=#SameRowID AND InitialTableMasterID=#Association_ITM_ID)
IF(ISNULL(#T04CMID,0)<> 0)
BEGIN
INSERT INTO #tmpAssessmentRows
(PrimaryKeyTableID,ColumnID,Value)
VALUES(#T04PKID,#T04CMID,#T04Value)
END
END
FETCH NEXT FROM GetSameRowIDs
INTO #SameRowID
END
CLOSE GetSameRowIDs
DEALLOCATE GetSameRowIDs
SELECT PKP.PatientID,PKP.[Date],ColumnID,Value into tmpAssesessment_Cast
FROM #tmpAssessmentRows AR
INNER JOIN dbo.PrimaryKeyForPredicting PKP ON AR.PrimaryKeyTableID=PKP.PrimaryKeyTableID
order by PKP.PrimaryKeyTableID
-----------------------------
--Logic for assesment_cast table creation from the data in rows
------------------------------
INSERT INTO #ColWithAliasTbl
SELECT ColumnID,[ColumnName]
FROM [dbo].[PrimaryKeyForModeling]
WHERE ColumnID IN (SELECT Distinct ColumnID FROM tmpAssesessment_Cast)
While EXISTS (SELECT colID,colName FROM #ColWithAliasTbl)
Begin
SELECT #ColID='['+CONVERT(VARCHAR,min(colID))+'],' FROM #ColWithAliasTbl
SELECT #ColName='['+CONVERT(VARCHAR,colID)+'] AS '''+ colName+''',' FROM #ColWithAliasTbl WHERE colID = (SELECT min(colID) FROM #ColWithAliasTbl)
SET #AllColID = #AllColID+#ColID
SET #AllColName = #AllColName+#ColName
DELETE from #ColWithAliasTbl Where colID = (SELECT min(colID) FROM #ColWithAliasTbl)
End
print #AllColID
print LEN(#AllColID)
SET #AllColID = SUBSTRING(#AllColID, 1, LEN(#AllColID)-1)
print '2'
SET #AllColName = SUBSTRING(#AllColName, 1, LEN(#AllColName)-1)
print '3'
SET #PivotTBL = 'SELECT patientID, [date], '+#AllColName +
' into assessment_cast FROM (SELECT * FROM [dbo].[tmpAssesessment_Cast]) KVS
PIVOT (Max(Value) FOR [ColumnID] IN ('+#AllColID+') ) pvt order by 1'
EXEC(#PivotTBL)
--Drop temporary table
IF OBJECT_ID('dbo.tmpAssesessment_Cast', 'U') IS NOT NULL
DROP TABLE dbo.tmpAssesessment_Cast;
DROP TABLE #tmpAssessmentRows
--Return the assessment_cast table data
SELECT * FROM assessment_cast
END TRY
BEGIN CATCH
-- Raise an error with the details of the exception
DECLARE #ErrMsg nvarchar(4000), #ErrSeverity INT,#ErrorState INT
SELECT #ErrSeverity=ERROR_SEVERITY(),
#ErrMsg= ERROR_MESSAGE(),
#ErrorState=ERROR_STATE();
RAISERROR(#ErrMsg, #ErrSeverity, #ErrorState)
EXEC sp_addmessage 50005,#ErrSeverity,#ErrMsg,'us_english', 'with_log'
END CATCH
END
GO
I have a stored procedure where I am declaring an int variable that needs to be populated using a dynamic sql
CREATE PROCEDURE USP_aTABLE_ADD
/*
stored procedure variables
*/
AS
DECLARE #count int
SET #count = 1
DECLARE #qry nvarchar(max)
/*
SET UP #qry which will look like this
SELECT #count = count(*) FROM aTABLE WHERE (col1 = 'val1' AND col2 = 'val2'...)
*/
/*
How to get the value of #count so that I can continue with add process
*/
IF #count = 0
BEGIN
/*add logic*/
END
Use sp_executeSQL and an output parameter:
DECLARE #count INT = 1
DECLARE #qry NVARCHAR(MAX)
SET #qry = N'set #count = (....)'
EXEC sp_executesql #qry, N'#count INT OUTPUT', #count OUTPUT
SELECT #count
You could try and work with a temporary table like this
DECLARE #tmp TABLE(cnt INT)
DECLARE #qry nvarchar(max)
-- Insert the count returned by dynamic SQL into temp table
SET #qry = 'SELECT COUNT(*) FROM Table WHERE condition'
INSERT INTO #tmp EXEC(#qry)
DECLARE #count INT
SET #count = (SELECT TOP 1 cnd FROM #tmp)
I want get the value from Exec(#sql) and assign to #Rowcount(int)
Here is my query:
'SET #RowCount = (select count(*)
FROM dbo.Comm_Services
WHERE CompanyId = '+cast(#CompanyId as char)+' and '+#condition+')'
On the one hand you could use sp_executesql:
exec sp_executesql N'select #rowcount=count(*) from anytable',
N'#rowcount int output', #rowcount output;
On the other hand you could use a temporary table:
declare #result table ([rowcount] int);
insert into #result ([rowcount])
exec (N'select count(*) from anytable');
declare #rowcount int = (select top (1) [rowcount] from #result);
DECLARE #nReturn int = 0
EXEC #nReturn = Stored Procedure
Was playing with this today... I believe you can also use ##ROWCOUNT, like this:
DECLARE #SQL VARCHAR(50)
DECLARE #Rowcount INT
SET #SQL = 'SELECT 1 UNION SELECT 2'
EXEC(#SQL)
SET #Rowcount = ##ROWCOUNT
SELECT #Rowcount
Then replace the SELECT 1 UNION SELECT 2 with your actual select without the count. I'd suggest just putting 1 in your select, like this:
SELECT 1
FROM dbo.Comm_Services
WHERE....
....
(as opposed to putting SELECT *)
Hope that helps.
that's my procedure
CREATE PROC sp_count
#CompanyId sysname,
#codition sysname
AS
SET NOCOUNT ON
CREATE TABLE #ctr
( NumRows int )
DECLARE #intCount int
, #vcSQL varchar(255)
SELECT #vcSQL = ' INSERT #ctr FROM dbo.Comm_Services
WHERE CompanyId = '+#CompanyId+' and '+#condition+')'
EXEC (#vcSQL)
IF ##ERROR = 0
BEGIN
SELECT #intCount = NumRows
FROM #ctr
DROP TABLE #ctr
RETURN #intCount
END
ELSE
BEGIN
DROP TABLE #ctr
RETURN -1
END
GO
If i understand you correctly, (i probably don't)
'SELECT #RowCount = COUNT(*)
FROM dbo.Comm_Services
WHERE CompanyId = ' + CAST(#CompanyId AS CHAR) + '
AND ' + #condition