bad string in dynamic sql and context info - sql

This is so strange! The following code is a t-sql.
BEGIN
DECLARE #cinfo VARBINARY(128) = CAST('aud:83/53784862/1' AS VARBINARY(128));
DECLARE #csinfo VARCHAR(128) = CAST(CONTEXT_INFO() AS VARCHAR(128));
SET #csinfo = '<root><value>' + REPLACE(RIGHT(#cinfo, LEN(#cinfo) - 4), '/', '</value><value>') + '</value></root>';
PRINT #csinfo
SET CONTEXT_INFO #cinfo;
DECLARE #sql VARCHAR(MAX) = '
DECLARE #cinfo VARCHAR(128) = CAST(CONTEXT_INFO() AS VARCHAR(128));
DECLARE #csinfo VARCHAR(512) = ''<root><value>'' + REPLACE(RIGHT(#cinfo, LEN(#cinfo) - 4), ''/'', ''</value><value>'') + ''</value></root>'';
PRINT #csinfo
'
EXEC(#sql)
END
This is the output:
<root><value>83</value><value>53784862</value><value>1</value></root>
<root><value>83</value><value>53784862</value><value>1
Why </value></root> is not appended!

I found the solution.
DECLARE #cinfo VARCHAR(128) = REPLACE(CAST(CAST(CONTEXT_INFO() AS VARCHAR(128)) COLLATE SQL_Latin1_General_CP1_CI_AS AS VARCHAR(128)), CHAR(0), '');
this will repair the string convert from CONTEXT_INFO().

Related

Get value of SQL Var conformed on varchar text

I have the next script example:
DECLARE #lCode INT
DECLARE #lText VARCHAR(400)
DECLARE #lConditionName VARCHAR(40)
DECLARE #Aux VARCHAR(400)
SET #lCode = 1234;
SET #lConditionName = 'Code'
SET #Aux = '#l' + #lConditionName
SET #lText = 'SELECT * FROM Table WHERE Code = ' + #Aux
PRINT #lText
The result is:
SELECT * FROM Table WHERE Code = #lCode
How can i obtein the value of #Aux Var like this?
SELECT * FROM Table WHERE Code = 1234
DECLARE #lCode INT
DECLARE #lText NVARCHAR(400)
DECLARE #lConditionName NVARCHAR(40)
DECLARE #Aux NVARCHAR(400)
SET #lCode = 1234;
SET #lConditionName = N'Code'
SET #Aux = N'#l' + #lConditionName
SET #lText = N'SELECT * FROM Table WHERE Code = ' + #Aux
PRINT #lText
EXEC sp_executesql #lText, N'#lcode INT', #lcode
You can try this :
DECLARE #lCode INT
DECLARE #lText NVARCHAR(400)
DECLARE #lConditionName NVARCHAR(40)
DECLARE #Aux NVARCHAR(400)
SET #lCode = 1234;
SET #lConditionName = N'Code'
SET #Aux = N'#l' + #lConditionName
SET #lText = N'SELECT * FROM Table WHERE Code = ' + #Aux
set #lText = N'Print ' + #Aux
print #lText
EXEC sp_executesql #lText, N'#lcode INT', #lcode
Output
Print #lCode
1234

How to parse an array in sql server

I created a stored procedure that looks like this.
CREATE PROCEDURE [EXP_RfPickAfter] (
#SESSIONVALUE xml,
#WorkDSArray nvarchar(max),
#UserSignonDS nvarchar(max),
#Direction nvarchar(max),
#ImmediateCount nvarchar(max),
#CCWorkUnit nvarchar(max),
#PartialPick nvarchar(max),
#RETURNVALUE nvarchar(max) output
)
AS
SET NOCOUNT ON;
#workDSArray has this long string in it
924WORK0924841SEQUENCE8410841842EQUIPMENT_LOC842842843PARENT_LOGISTICS_
UNIT843843844REFERENCE_TYPE844Order844845INVENTORY_AT_
PD845845846FROMVER846None846847INTERNAL_NUM8476851842847848START_
DATE_TIME848848849INCHKDIG849849850TOTAL_VOLUME8500850851
TO_LOC851SHIP-1851852INTERNAL_NUM_TYPE852Shipment852853
WEIGHT_UM853LB853854COMPANY854SHOS854855QUANTITY_UM855CS855856OUTGOING_
PD_LOC856856857WORK_TYPE857LPNPick857858END_DATE_TIME858858859
ACTUALFROMWHS859L455859860LOT860860861WORK_ZONE1861861862
TOCONTAINERID8621862863INVER863863864TRACK_CONTAINERS864N864865
TO_LOC_INV_ATTRIBUTES_ID865865866CYCLE_COUNT866866867
LAUNCH_NUM86716949391867868ACTUALTOLOC868-jisavm3868869
FROM_CHECK_DIG869869870FROM_WHS870L455870871
WORK_GROUP871Picking871872INTERNAL_LINE_NUM187232612518872873
VOLUME_UM873873874ACTUALFROMLOC874NF-1-F-28-1874875
INTERNAL_REQ_NUM87520774185875876TO_WHS876L455876877
INTERNAL_LINE_NUM87732612518877878TREE_UNIT87826385537878879
INWRKZONE879879880PUTLOC880SHIP-1880881CONTAINER_ID88116489660881882
INTERNAL_CONTAINER_NUM88226385537882883FROMTRKCONT883Y883884
PARENT_CONTAINER_NUM8840884885CONVERTED_QTY_UM885CS885886
ACTUALTOWHS886L455886887OUTWRKZONE887887888
VERIFICATION_METH888None888889USER_DEF4889 L455-RS 2889890
REFERENCE_ID890XKJNNLJN890891LOGISTICS_UNIT89116489660891892
MESSAGE_ID892892893PICKLOC893NF-1-F-28-1893894
CURRENTLOC894F894895TREE_UNIT_ID89516489660895897
TOCONTAINERID089716489660897898TOTAL_WEIGHT8981898899
TOTAL_VALUE8990899900TO_CHECK_DIG900900901OUTCHECKDIG901901902
TO_QTY9020902903INTRKCONT903903904FROM_LOC_INV_ATTRIBUTES_ID904904905
INTERNAL_INSTRUCTION_NUM90520699485905906ITEM_DESC906MSF21D4MDE -
Refrigerator906907ITEM907SHOS-STOCK907908
COMPLETEDBYUSER908jisavm3908909
TRANSPORT_CONT_ID90916489660909910OUTTRKCONT910910911ACCOUNT911
Store #9449911912INCOMING_PD_LOC912912913INVENTORY_TRACKING913Y913914
LOCATION_CLASS914Shipping Dock914915FROM_QTY9151915916OUTVERMETH916916917
CONVERTED_QTY9171917918QUANTITY9181918919
PARENT_INSTR91920699484919920
FROM_LOC920NF-1-F-28-1920921WORK_ZONE921W-
Returns921922WORK_UNIT92216489660922923QTY
CONFIRMED9231923924925WORK9251925
I am trying to parse containerID and its value from this string and use it in a select statement in my stored procedure, but I am unsure how to parse only the containerID.
Any help would be appreciated
This is what I did to get the right ID I had to trigger off of something else. This is not ideal because I don't know if the string will change. If anybody knows a better way please post and thank you #ymuribbi you helped me out a ton. I edited this to show my full solution just in case someone else runs into this issue.
DECLARE #WorkDSArray nvarchar(max);
SET #WorkDSArray= '924WORK0924841SEQUENCE8410841842EQUIPMENT_LOC842842843PARENT_LOGISTICS_UNIT843843844REFERENCE_TYPE844Order844845INVENTORY_AT_PD845845846FROMVER846None846847INTERNAL_NUM8476851842847848START_DATE_TIME848848849INCHKDIG849849850TOTAL_VOLUME8500850851TO_LOC851SHIP-1851852INTERNAL_NUM_TYPE852Shipment852853WEIGHT_UM853LB853854COMPANY854SHOS854855QUANTITY_UM855CS855856OUTGOING_PD_LOC856856857WORK_TYPE857LPN Pick857858END_DATE_TIME858858859ACTUALFROMWHS859L455859860LOT860860861WORK_ZONE1861861862TOCONTAINERID8621862863INVER863863864TRACK_CONTAINERS864N864865TO_LOC_INV_ATTRIBUTES_ID865865866CYCLE_COUNT866866867LAUNCH_NUM86716949391867868ACTUALTOLOC868-jisavm3868869FROM_CHECK_DIG869869870FROM_WHS870L455870871WORK_GROUP871Picking871872INTERNAL_LINE_NUM187232612518872873VOLUME_UM873873874ACTUALFROMLOC874NF-1-F-28-1874875INTERNAL_REQ_NUM87520774185875876TO_WHS876L455876877INTERNAL_LINE_NUM87732612518877878TREE_UNIT87826385537878879INWRKZONE879879880PUTLOC880SHIP-1880881CONTAINER_ID88116489660881882INTERNAL_CONTAINER_NUM88226385537882883FROMTRKCONT883Y883884PARENT_CONTAINER_NUM8840884885CONVERTED_QTY_UM885CS885886ACTUALTOWHS886L455886887OUTWRKZONE887887888VERIFICATION_METH888None888889USER_DEF4889 L455-RS 2889890REFERENCE_ID890XKJNNLJN890891LOGISTICS_UNIT89116489660891892MESSAGE_ID892892893PICKLOC893NF-1-F-28-1893894CURRENTLOC894F894895TREE_UNIT_ID89516489660895897TOCONTAINERID089716489660897898TOTAL_WEIGHT8981898899TOTAL_VALUE8990899900TO_CHECK_DIG900900901OUTCHECKDIG901901902TO_QTY9020902903INTRKCONT903903904FROM_LOC_INV_ATTRIBUTES_ID904904905INTERNAL_INSTRUCTION_NUM90520699485905906ITEM_DESC906MSF21D4MDE - Refrigerator906907ITEM907SHOS-STOCK907908COMPLETEDBYUSER908jisavm3908909TRANSPORT_CONT_ID90916489660909910OUTTRKCONT910910911ACCOUNT911Store #9449911912INCOMING_PD_LOC912912913INVENTORY_TRACKING913Y913914LOCATION_CLASS914Shipping Dock914915FROM_QTY9151915916OUTVERMETH916916917CONVERTED_QTY9171917918QUANTITY9181918919PARENT_INSTR91920699484919920FROM_LOC920NF-1-F-28-1920921WORK_ZONE921W-Returns921922WORK_UNIT92216489660922923QTYCONFIRMED9231923924925WORK9251925'
DECLARE #ContainerID integer;
SET #ContainerID = CHARINDEX('TREE_UNIT_ID', #WorkDSArray);
DECLARE #ID nvarchar(max);
SET #ID = SUBSTRING(#WorkDSArray, #ContainerID,300)
SELECT #ID;
DECLARE #ActualContainerID nvarchar(max);
SET #ActualContainerID = SUBSTRING(#ID, 54, 9)
SET #ActualContainerID = REPLACE(#ActualContainerID, CHAR(31), '')
DECLARE #User integer
DECLARE #UserID nvarchar(max)
SET #User = CHARINDEX('COMPLETEDBYUSER', #WorkDSArray);
SET #UserID = SUBSTRING(#WorkDSArray, #User,27)
DECLARE #ActualUserID nvarchar(max);
SET #ActualUserID = SUBSTRING(#UserID, 20, 8)
SET #ActualUserID = REPLACE(#ActualUserID, CHAR(31), '')
DECLARE #Shipment nvarchar(max)
SET #Shipment = (SELECT CASE WHEN SH.COMPANY = 'SHOS' THEN '' ELSE SH.SHIPMENT_ID + '|' +
SH."ROUTE" + '|' +
SH."STOP" + '|' +
SH.COMPANY + '|' +
LEFT(SH.CUSTOMER_NAME,25) + '|' +
LEFT(SH.SHIP_TO_ADDRESS1,25) + '|' +
CASE WHEN SH.SHIP_TO_ADDRESS2 <> '' THEN SH.SHIP_TO_ADDRESS2 + '|'
ELSE '' END +
LEFT(SH.SHIP_TO_CITY,25) + '|' +
LEFT(SH.SHIP_TO_STATE,25) + '|' +
LEFT(SH.SHIP_TO_POSTAL_CODE,25) END
FROM SHIPMENT_HEADER SH
JOIN SHIPPING_CONTAINER SC
ON SC.INTERNAL_SHIPMENT_NUM = SH.INTERNAL_SHIPMENT_NUM
WHERE SC.CONTAINER_ID = #ActualContainerID)
DECLARE #ShipmentID nvarchar(max)
SET #ShipmentID = SUBSTRING(#Shipment,0,9)
--select top 1 device_name from dbo.DOCUMENT_ROUTING where document_type = 'HJBT_REC' and user_name = #user
INSERT INTO [jbh].[PRT_REQ_WRK]
([REQ_REF_TYP], [REQ_REF_I], [PRT_DVC_NM], [REQ_TMPL_NM], [REQ_VAL], [PRT_STT], [PRT_PRS_TYP], [PRT_Q], [CRT_S], [CRT_UID], [CRT_PGM_C], [LST_UPD_S], [LST_UPD_UID], [LST_UPD_PGM_C])
VALUES (
#ShipmentID, --[REQ_REF_TYP]
'123abc', --[REQ_REF_I]
'LB01885', --[PRT_DVC_NM]
'HJBT_Shipping_Label.lbl', --[REQ_TMPL_NM]
#Shipment, --[REQ_VAL]
0, --[PRT_STT]
'LABEL', --[PRT_PRS_TYP]
1, --[PRT_Q]
CURRENT_TIMESTAMP, --[CRT_S]
#ActualUserID, --[CRT_UID]
'WMSPrintService', --[CRT_PGM_C]
CURRENT_TIMESTAMP, --[LST_UPD_S]
'JISAVM3', --[LST_UPD_UID]
'WMSPrintService') --[LST_UPD_PGM_C]
As #hogan stated in his comment, you can use string operators for extraction with some while and if-else statements
-- I am editing my answer.
To retrieve the container ID you use a store procedure like this:
create proc getid (#string varchar(max)) as
declare #containerIdIndex int = (select charindex('CONTAINER_ID',#string))
declare #internalContainerIndex int = (select(Charindex('INTERNAL_CONTAINER', #string)))
declare #range int = #internalContainerindex-#containerIdindex+12
declare #start int = #containerIdIndex+12 --12 is to pass the 'Container_ID'
declare #containerId varchar(max)
set #containerId = substring(#string,#start,#range)
print #containerId

Incorrect syntax near '=' while trying to call a stored procedure in T-sql

I am calling a stored procedure called Searchprocedure. I get an error at line where I am calling it. I have not made any changes to the parameters passed in the procedure and it was called just fine with same calling statement earlier.
Exec SearchProcedure #firstname = 'Simran', #middlename = 'kaur', #lastname = 'Khurana', #City = 'Delhi'
What's wrong with the syntax that is gives the error that says:
Incorrect syntax near '='
Edit:
Statement where I did :
set #sql = 'declare ' + '#Temp'+ #colVar + ' int'
exec(#sql)
select #sql as 'SQLFORDECLARATIONS
outputs
declare #TempMiddleName int
yet when I try to set value in the variable gives error that it should be declared first.
The set statement results in :
select #TempMiddleName=dbo.[MatchMiddleName](MiddleNameFromUser,MiddleNameFromTable,0)
which is what is should be yet it not able to see the declared variable
The stored procedure is as follows:
create procedure SearchProcedure
(
#firstname nvarchar(20),
#middlename nvarchar(20) = null,
#lastname nvarchar(20),
#DOB Date = null,
#SSN nvarchar(30)= null,
#ZIP nvarchar(10)= null,
#StateOfResidence nvarchar(2)= null,
#City nvarchar(20)= null,
#StreetName nvarchar(20)= null,
#StreetType nvarchar(20)= null,
#BuildingNumber int= null,
#Aptnumber nvarchar(10)= null
)
As
DECLARE #sSQL NVARCHAR(2000), #Where NVARCHAR(1000) = ' '
declare #Percent int,
#FN nvarchar(20),
#MN nvarchar(20) = null,
#LN nvarchar(20),
#DateOfB Date = null,
#SSNumber nvarchar(30)= null,
#ZIPCode nvarchar(10)= null,
#StateOfRes nvarchar(2)= null,
#CityOfRes nvarchar(20)= null,
#StreetNameRes nvarchar(20)= null,
#StreetTypeRes nvarchar(20)= null,
#BuildingNumberRes int= null,
#AptnumberRes nvarchar(10)= null
set #Percent = 0
create table #results
(
firstname nvarchar(20) not null,
middlename nvarchar(20),
lastname nvarchar(20)not null,
PercentageMatch int not null,
DOB Date,
SSN nvarchar(30),
ZIP nvarchar(10),
[State] nvarchar(2),
City nvarchar(20),
StreetName nvarchar(20),
StreetType nvarchar(20),
BuildingNumber int,
Aptnumber nvarchar(10)
)
declare c Cursor local static Read_only
for
SELECT * from dbo.Patients where firstname = #firstname
open c
fetch next from c into #FN,
#MN,
#LN,
#DateOfB,
#SSNumber,
#ZIPCode,
#StateOfRes,
#CityOfRes,
#StreetNameRes,
#StreetTypeRes,
#BuildingNumberRes,
#AptnumberRes
while ##FETCH_STATUS = 0 BEGIN
/*set #Percent = dbo.[MatchLastName](#lastname, #LN, #Percent)
set #Percent = dbo.[MatchMiddleName](#middlename, #MN, #Percent)
set #Percent = dbo.[MatchCity](#City, #CityOfRes, #Percent)*/
Exec [dbo].[OutputProcedure] #lastname, #LN, #middlename, #MN,#City, #CityOfRes, #Percent output
Insert into #results values
(#FN,#MN,#LN,#Percent, #DateOfB,#SSNumber, #ZIPCode,#StateOfRes,#CityOfRes,#StreetNameRes,#StreetTypeRes,#BuildingNumberRes,#AptnumberRes)
fetch next from c into #FN,
#MN,
#LN,
#DateOfB,
#SSNumber,
#ZIPCode,
#StateOfRes,
#CityOfRes,
#StreetNameRes,
#StreetTypeRes,
#BuildingNumberRes,
#AptnumberRes
end
select * from #results order by PercentageMatch desc
IF OBJECT_ID('tempdb..#results') IS NOT NULL DROP TABLE #results
go
OutputProcedure code is as follows:
CREATE Procedure OutputProcedure
(
#LastNameFromUser nvarchar(20) = null,
#LastNameFromTable nvarchar(20),
#MiddleNameFromUser nvarchar(20) = null,
#MiddleNameFromTable nvarchar(20) = null,
#CityFromUser nvarchar(20) = null,
#CityFromTable nvarchar(20) = null,
#Percentage int out
)
AS
BEGIN
select 'OUTPUTPROCEDURECALLED'
declare #maxvalue int
DECLARE #variableTable TABLE (
idx int identity(1,1),
matchvalue nvarchar(15))
INSERT INTO #variableTable(matchvalue) values ('MiddleName')
INSERT INTO #variableTable(matchvalue) values ('LastName')
INSERT INTO #variableTable(matchvalue) values ('City')
SELECT * FROM #variableTable
DECLARE #counter int
declare #sql nvarchar(100)
declare #sql2 nvarchar(25), #finalResult nvarchar(100)
declare #sql3 nvarchar(300), #sql4 nvarchar(15), #tempresultStore nvarchar(20), #temp int, #temp2 int, #average int
SET #counter = 1
SELECT #maxvalue = (SELECT MAX(idx) FROM #variableTable)
select #maxvalue as 'MAXVALUE'
WHILE(#counter <= #maxvalue)
BEGIN
DECLARE #colVar nvarchar(15)
SELECT #colVar = matchvalue FROM #variableTable WHERE idx = #counter
set #sql = 'declare ' + '#Temp'+ #colVar + ' int'
exec(#sql)
select #sql as 'SQLFORDECLARATIONS'
/*set #temp = CHARINDEX(' ',#sql)
select #temp as 'resultofcharindex'
set #temp2 = LEN(#sql) - (#temp)
SELECT #temp2 AS 'AFTERADDING1'
set #tempresultStore = right(#sql, #temp2)*/
set #tempresultStore = 'Temp'+#colVar
SELECT #tempresultStore AS 'FINALCUTPART'
set #sql3 = 'set ' + ' ' + #tempresultStore + '=' + 'dbo.[Match' + #colVar + '](' + #colVar + 'FromUser' + ',' + #colVar + 'FromTable' + ',' + '0)'
EXEC(#sql3)
select #sql3 as 'check sql query formed'
set #finalResult = #finalResult + #tempresultStore
select #finalResult as 'SUM'
SET #counter = #counter + 1
select #counter as 'COUNTERVALUE'
END
set #Percentage = #finalResult/#maxvalue
SELECT #Percentage AS 'FINALRESULT'
RETURN
END
--Setting variable in Dynamic SQL
DECLARE
#sql NVARCHAR(MAX),
#Name NVARCHAR(100)
SET #Name = '#B2E0EB1A'
SET #sql =
'
DECLARE #MyVar NVARCHAR(100)
SELECT TOP 1 #MyVar = name FROM sys.objects WHERE name LIKE ''%a''--Escaping single quote with double quote
PRINT #MyVar
'
EXEC(#sql)
SET #sql =
'
DECLARE #MyVar NVARCHAR(100)
SET #MyVar = '''+(SELECT TOP 1 name FROM sys.objects WHERE name LIKE '%a')+'''--Escaping single quote with double quote
PRINT #MyVar
'
EXEC(#sql)
SET #sql =
'
DECLARE #MyVar NVARCHAR(100)
SET #MyVar = '''+#Name+'''--Escaping single quote with double quote
PRINT #MyVar
'
EXEC(#sql)
SET #sql =
'
DECLARE #MyVar NVARCHAR(100)
SET #MyVar = ''#B2E0EB1A''--Escaping single quote with double quote
PRINT #MyVar
'
EXEC(#sql)
If you want to get output variable from your dynamic query you have to use sp_executesql procedure instead of EXEC()
Study this code
DECLARE #DynamicSQLOutput NVARCHAR(100)
DECLARE #SQL nvarchar(500);
DECLARE #ParmeterDefinition nvarchar(500);
--in this variabe you write the variables which you want to be declared in the dynamic sql without using the declare
SET #ParmeterDefinition = N'#FinalOutputResultInDynamicSQL NVARCHAR(100) OUTPUT';
--here you write your dynamic code
SELECT #SQL = N'SET #FinalOutputResultInDynamicSQL = ''test'' '
EXEC sp_executesql
#SQL, --Execute code
#ParmeterDefinition, -- Define Parameters
#FinalOutputResultInDynamicSQL = #DynamicSQLOutput OUTPUT --Get output
--Note that #FinalOutputResultInDynamicSQL is only defined in #ParmeterDefinition but not outside of the dynamic sql
PRINT #DynamicSQLOutput;
I think too many things wrong in your Dynamic sql. I found one
SET #sql3 = 'set ' + ' ' + #tempresultStore + ' = ' + 'dbo.[Match'
+ #colVar + '](' + #colVar + 'FromUser' + ',' + #colVar
+ 'FromTable' + ',' + '0)'
In the above code instead of Set use Select. Looks like you are selecting from a UDF. Try this
SET #sql3 = 'Select ' + ' ' + #tempresultStore + ' = ' + 'dbo.[Match'
+ #colVar + '](' + #colVar + 'FromUser' + ',' + #colVar
+ 'FromTable' + ',' + '0)'
Note : To debug Dynamic Sql before Exec #sql just use print #sql to check the syntax and other stuff in generated sql
I can't find any error and can run the exec without anerror message.
Edit: After I created the (now avialbe) output procedure and uncomment its call, I'm getting the error too...
Still investigating
Edit2:
In the Output procedure you have to use
set #sql = 'declare ' + '#Temp'+ #colVar + ' int' (# before Temp) and
set #sql3 = 'set ' + ' #' + #tempresultStore" (additional # after the 'set'.
Btw: you can exec more than one statement in Dynamic SQL so you could use f.e. exec (#sql + '; ' + #sql3);

How to find the First Character starting in SQL Server 2008

DECLARE #input NVARCHAR(MAX) = 'Create Procedure Test'
DECLARE #SearhString NVARCHAR(MAX) = 'Procedure'
DECLARE #index BIGINT = CHARINDEX(#keyword, #input)
1- I want to find the length of the next character starting after string Procedure
2- After that I want to check if the dbo string exists after that length to the specified location.
Suppose the first character Test starting at position 14 after string Procedure, so I have to use
DECLARE #String varchar(20) = SUBSTRING(#input, 21, 10)
Declare #StringIndex BIGINT = CHARINDEX('dbo.', #String)
Declare #FirstCharacterIndex BIGINT(This will be the index of the first character)
If #String not contains string dbo then stuff MySchema before string Test.
Please suggest.
UPDATE
I have updated my question 22 is the result of #index + #FirstCharacterIndex + 9
#index = 8
#FirstCharacterIndex = 4(3 count for spaces and 4th is for first character)
9 = No. of characters of string Procedure
try this sql below:
DECLARE #input NVARCHAR(MAX) = 'Create Procedure Test';
DECLARE #input2 NVARCHAR(MAX) = 'Create Procedure dbo Test';
DECLARE #SearchString NVARCHAR(MAX) = 'Procedure';
DECLARE #index BIGINT = CHARINDEX(#SearchString, #input);
select #input, #SearchString as searchstring, #index as Index_SearchString , #index +len(#SearchString) as Last_CharacterOfSearchString
, charIndex('Test', #input,#index +len(#SearchString)) as test_Index
, charIndex('dbo', #input,#index +len(#SearchString)) as dbo_Index
, substring(#input, 0, #index +len(#SearchString)) as str1
, substring(#input, #index +len(#SearchString), len(#input)-#index +len(#SearchString)) as str2
Declare #dbo_Index int
Declare #str1 nvarchar(max), #str2 nvarchar(max)
set #dbo_Index = charIndex('dbo', #input,#index +len(#SearchString))
--select #dbo_Index
if #dbo_Index = 0
begin
set #str1 = substring(#input, 0, #index +len(#SearchString))
set #str2 = substring(#input, #index +len(#SearchString), len(#input)-#index +len(#SearchString))
select #str1 + ' ' + 'MySchema' + #str2
end
--,charIndex('dbo',#input2, #index +len(#SearchString)) as dbo_Index
Updated:
objective: Get the "Under Fire" first character index ("U")
DECLARE #input2 NVARCHAR(MAX) = 'Create Procedure Under Fire Test';
DECLARE #SearchString NVARCHAR(MAX) = 'Procedure';
--,charIndex('dbo',#input2, #index +len(#SearchString)) as dbo_Index
select substring(#input2,17,25)
, CHARINDEX(#SearchString,#input2,0) + len(#SearchString) as LastIndexOf_Procedure
, CHARINDEX('Test',#input2,0)
,len(#input2)
,substring(#input2, CHARINDEX(#SearchString,#input2,0) + len(#SearchString), CHARINDEX('Test',#input2,0)- (CHARINDEX(#SearchString,#input2,0)+len(#SearchString)))
set #SearchString= Ltrim(rtrim(substring(#input2, CHARINDEX(#SearchString,#input2,0) + len(#SearchString), CHARINDEX('Test',#input2,0)- (CHARINDEX(#SearchString,#input2,0)+len(#SearchString)))))
select #SearchString
select
#input2
,#SearchString as SearchString
,CHARINDEX(#SearchString,#input2,0) as FirstCharacterIndex

Not able to get INSERT of SP to work

I am not able to get the INSERT portion of the below procedure to work. Any help would be appreciated....
#currTable varchar(100),
#ID int,
#short_Text varchar(250),
#brief_Descrip varchar(250) = Null,
#needsTranslation varchar(10) = Null,
#prev_LangString varchar(250) = Null,
#lang_String varchar(250) = Null,
#original_lang_String varchar(250) = Null,
#StringID_from_Master int,
#GUID varchar(250) = Null
AS
BEGIN
SET NOCOUNT ON;
DECLARE #submitDate1 DATETIME;
SET #submitDate1 = GETDATE()
SET #prev_LangString = #original_lang_String
DECLARE #sql NVARCHAR(MAX);
SELECT #sql = N' UPDATE ' + QUOTENAME(#currTable) + ' SET [lang_String] = ''' + REPLACE(#lang_String,'''','''''') + ''', [date_Changed] = ''' + convert(varchar(20), #submitDate1) + ''', [prev_LangString] = ''' + #prev_LangString + ''', [needsTranslation] = ''' + #needsTranslation + ''' WHERE ID = ' + RTRIM(#ID) + '; ';
EXEC sp_executesql #sql;
INSERT tblPendingDBUpdates
( stringMasterID,
databaseName,
databaseStringID,
englishText,
foreignLangText,
submitDate,
GUID
)
SELECT #StringID_from_Master,
Database_Name,
dbKeyID_ofStringName,
#short_Text,
#lang_String,
#submitDate1,
#GUID
FROM tblDBUsage
WHERE tblUniquetblStringsMaster_ID = #StringID_from_Master;
END
I tried this code block only and no luck it did not INSERT to tblPendingDBUpdates.... Noticed something weird about GUID as field name so changed it in table also...
AS
BEGIN
SET NOCOUNT ON;
DECLARE #submitDate1 DATETIME;
SET #submitDate1 = GETDATE()
-- SET #prev_LangString = #original_lang_String
DECLARE #sql NVARCHAR(MAX);
DECLARE #currTable varchar(100);
SET #currTable = 'tblLangenUS'
DECLARE #ID INT;
SET #ID = 2
DECLARE #short_Text varchar(250);
SET #short_Text = 'testing99'
DECLARE #StringID_from_Master INT;
SET #StringID_from_Master = 2
DECLARE #lang_String varchar(250);
SET #lang_String = 'testing9999'
DECLARE #GUID1 varchar(250);
SET #GUID1 = 'Null'
INSERT tblPendingDBUpdates
( stringMasterID,
databaseName,
databaseStringID,
englishText,
foreignLangText,
submitDate,
GUID1
)
SELECT #StringID_from_Master,
Database_Name,
dbKeyID_ofStringName,
#short_Text,
#lang_String,
#submitDate1,
#GUID1
FROM tblDBUsage
WHERE tblUniquetblStringsMaster_ID = #StringID_from_Master;
END
I don't really know what you need but here is a stored proc with your declarations
CREATE PROCEDURE TestProc
AS
BEGIN
SET NOCOUNT ON;
DECLARE #submitDate1 DATETIME
SET #submitDate1 = GETDATE()
DECLARE #sql NVARCHAR(MAX)
DECLARE #StringID_from_Master INT
SET #StringID_from_Master = 2
DECLARE #short_Text varchar(250)
SET #short_Text = 'testing99'
DECLARE #lang_String varchar(250)
SET #lang_String = 'testing9999'
DECLARE #GUID1 varchar(250)
SET #GUID1 = 'Null'
BEGIN
EXEC sp_executesql #sql
END
BEGIN
INSERT INTO tblPendingDBUpdates
(
stringMasterID,
databaseName,
databaseStringID,
englishText,
foreignLangText,
submitDate,
GUID1
)
SELECT
#StringID_from_Master,
Database_Name,
dbKeyID_ofStringName,
#short_Text,
#lang_String,
#submitDate1,
#GUID1
FROM tblDBUsage
WHERE tblUniquetblStringsMaster_ID = #StringID_from_Master
END
END
GO
Well as far I understand it ... change the SP code to below and try again ... most probably will work fine
CREATE PROCEDURE <SOME NAME>
AS
BEGIN
<ALL YOUR DECLARATION HERE>
BEGIN
EXEC sp_executesql #sql;
END
GO
BEGIN
INSERT INTO tblPendingDBUpdates
(stringMasterID,
databaseName,
databaseStringID,
englishText,
foreignLangText,
submitDate,
GUID1)
SELECT #StringID_from_Master,
Database_Name,
dbKeyID_ofStringName,
#short_Text,
#lang_String,
#submitDate1,
#GUID1
FROM tblDBUsage
WHERE tblUniquetblStringsMaster_ID = #StringID_from_Master;
END
END
GO
If your not getting an error message and inserting zero rows, than you select statement must not be returning anything.
what does this return?
select *
FROM tblDBUsage
WHERE tblUniquetblStringsMaster_ID = #StringID_from_Master
If you're first stored proc it didn't look like #StringID_from_Master ever got set. That could be your problem.