How to store a insert query of Hindi text inside a variable in SQL Server? - sql-server-2008

The query I am executing is inside a stored procedure but the text inside columns when in hindi language is appeared as ??? in table. How can this be fixed to normal by inserting text as well as through variables.
Declare #query as varchar(max);
Declare #value1 as nvarchar(max);
ALL i , j, k columns are of NVARCHAR TYPE
through text
set #query='Insert into Tablename(i,j,k)
Values(N''राम'',N''SHYAM'',N''HANUMAN'')'
through variables
set #value1=N'राम';
set #query='Insert into Tablename(i,j,k)
Values(N'''+#value1+''',N''SHYAM'',N''HANUMAN'')'

Related

Naming a cursor dynamically

Is it possible to name a cursor dynamically?
Something like this:
CREATE PROCEDUREdyn_cursor(INqueryTEXT, INnameTEXT)
READS SQL DATA
LANGUAGE SQL
COMMENT 'Simulate dynamic cursor'
BEGIN
DECLARE eof BOOL;
SET temp = 'cur_dyn'+name
DECLARE temp CURSOR FOR
SELECT * FROM dyn_view;
...
What I want is to achieve is to pass the name of the cursor as a input, can it be done?
Cheers!

How to check for a character in a string and replace that character before insert

Ok, this question involves one part of a complicated stored procedure which inserts new entities into several tables.
The part that I'm currently having difficulty with needs to work like so:
insert entity with original name
check if name of new entity contains any special characters listed in table A 'Characters'
if yes, than replace that character with a 'replacement character' from table A
EDIT: I've gotten this to partially work but still not finished. I'm still having a problem showing each combination of character replacements. Also in the case of a replacement character occurring more than once, such as the '.', the substitutions needs to happen independently of one another.
ex: #www.test&aol.com -> #wwwtest&aol.com, #www.test&aolcom
Here's a rough start, I know parts of this aren't going to work, but I thought it was a decent starting point:
declare #test varchar(50)
set #test = '#www.test&aol.com'
declare #len int, #ctr int
set #len = LEN(#test)
set #ctr = 1
declare #newName varchar(50)
declare #matchedChar table(match varchar(10),replaceChar varchar(10),processed int default(0))
declare #alternateEntities table(name varchar(50))
declare #repChar varchar(10)
declare #selectedChar varchar(1)
while #ctr<=#len
begin
--Insert matching characters and replacement characters into table variable,
--this is necessary for the # character, which has multiple replacement characters
insert into #matchedChar (match,replaceChar) select Character,ReplacementCharacter from tblTransliterations where Character = SUBSTRING(#test,#ctr,1)
--loop
while (select COUNT(*) from #matchedChar where processed = 0)>0
begin
--get the top character from table variable
set #selectedChar = (select top 1 match from #matchedChar where processed = 0)
--get replacement character
set #repChar = (select top 1 replaceChar from #matchedChar where processed = 0)
--replace character in name string
--set #newName = (select Replace(#test,#selectedChar,#repChar))
set #newName = (select STUFF(#test,CHARINDEX(#selectedChar,#test),1,#repChar))
--update table variable to move onto next character
update #matchedChar set processed = 1 where #repChar = replaceChar
--add name with replaced character to alternate entities table
insert into #alternateEntities (name) values (#newName)
end
set #ctr = #ctr+1
set #len = LEN(#test)
end
select * from #alternateEntities
Instead of looping, use set-based approach.
Create a temp table and populate column 'Words' of type NVARCHAR(100), call the temp table Invalid_Words
Create a column on Invalid_Words for each token and make the col type = bit
Update the temp table bit columns if a word contains the token through a series of update statements
You now have defined which tokens were matched for each word.
The next part is to replace.

What's wrong with the stored procedure

I have a table called Std_Components which acts like an index for list of components with associated tables. The column AssociatedTable holds the name of table that actually contains the component data.
Please check images below -
Here is table data for Std_SteeringPumps
I am trying to create a stored procedure that will copy Std_Components table as well as all associated tables with new name. For ex. Lets say if i provided 001 as a parameter to this stored procedure i should be able create new tables like C001_Components, C001_SteeringPumps and so on.
This is what I have done so far:
ALTER PROCEDURE [dbo].[sgi_sp_CreateTablesForNewCompany]
-- Add the parameters for the stored procedure here
#CompanyId varchar(5)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- declare variables
declare #qry as varchar(2000)
declare #compTblName as varchar(100)
set #compTblName = 'C'+#companyId +'_Components'
-- Check if table already exists
IF object_id(#compTblName) is not null
return
-- Create main component index table by copying standard component table --
set #qry = 'Select * into '+#compTblName+' From Std_Components;';
--print #qry
--execute (#qry)
set #qry =#qry + 'Update C'+#companyId +'_Components Set AssociatedTable=''C'+#companyId +'''+substring(AssociatedTable,4,200);';
--print #qry
--exec #qry
-- Create all child tables --
Select * Into #TempTbl From dbo.Std_Components
Declare #Id int
While (Select Count(*) From #TempTbl) > 0
Begin
declare #rowTableName as varchar(50)
declare #compNewTbl as varchar(50)
Select Top 1 #rowTableName=AssociatedTable, #Id = Id From #TempTbl
set #compNewTbl = 'C'+#companyId + substring(#rowTableName,4,200);
set #qry = #qry + 'Select * into '+#compNewTbl+' From ' + #rowTableName + ';'
--print #qry
--exec #qry
Delete #TempTbl Where Id = #Id
End
print #qry
exec #qry
END
Here is the output of the print statement for the query it generates -
Select * into C001_Components From Std_Components;
Update C001_Components Set AssociatedTable='C001'+substring(AssociatedTable,4,200);
Select * into C001_SteeringPumps From Std_SteeringPumps;
But when the stored procedure is executed, I get the following error -
Msg 203, Level 16, State 2, Procedure sgi_sp_CreateTablesForNewCompany, Line 56
The name 'Select * into C001_Components From Std_Components;Update C001_Components Set AssociatedTable='C001'+substring(AssociatedTable,4,200);Select * into C001_SteeringPumps From Std_SteeringPumps;' is not a valid identifier.
Can anybody help me out resolve this issue.
Thanks for sharing your time and wisdom.
The error you're getting is because the EXEC statement (the last line of the stored procedure) needs to have brackets around the #qry variable so that it becomes
exec(#qry)
Without the brackets it's treating the entire SQL string as stored procedure name.
The non valid indentifier is around the AssociatedTable part
Set AssociatedTable='C001'+substring(AssociatedTable,4,200); will not run as there is no scope for AssociatedTable to substring - the string needs to contain the name of the table completely to be able to be executed
Instead of
exec #qry;
You need
exec sp_executesql #qry;
You'll also need to change the type of #qry to NVARCHAR. Note that because of the dynamic sql, the proc is prone to SQL Injection and other escaping issues (i.e. ensure that #CompanyId is validated)

ms sql query on count occurence of words in text column

I have a table called webqueries with a column named qQuestion of data type text(sql server 2008). I want to create a count on words used in qQuestion (excluding 'and', 'is' etc). My goal is to see how many times a person has asked a question about a specific product.
You could create a table-valued function to parse words and join it to your query against qQuestion. In your schema, I recommend using varchar(8000) or varchar(max) instead of text. Meanwhile, the following should get you started:
create function [dbo].[fnParseWords](#str varchar(max), #delimiter varchar(30)='%[^a-zA-Z0-9\_]%')
returns #result table(word varchar(max))
begin
if left(#delimiter,1)<>'%' set #delimiter='%'+#delimiter;
if right(#delimiter,1)<>'%' set #delimiter+='%';
set #str=rtrim(#str);
declare #pi int=PATINDEX(#delimiter,#str);
while #pi>0 begin
insert into #result select LEFT(#str,#pi-1) where #pi>1;
set #str=RIGHT(#str,len(#str)-#pi);
set #pi=PATINDEX(#delimiter,#str);
end
insert into #result select #str where LEN(#str)>0;
return;
end
go
select COUNT(*)
from webqueries q
cross apply dbo.fnParseWords(cast(q.qQuestion as varchar(max)),default) pw
where pw.word not in ('and','is','a','the'/* plus whatever else you need to exclude */)

Stored Procedure Dynamic SQL stored result in variable

I have A stored procedure written
DECLARE #AreaID AS INT
DECLARE #DayPrior AS INT
DECLARE #TableName AS VARCHAR(50)
DECLARE #StoreQuery AS NVARCHAR(MAX)
DECLARE #SQL_ExtractDlSql AS NVARCHAR(MAX)
DECLARE #ParameterDefinition AS NVARCHAR(2000)
SET #AreaID = 1
SET #DayPrior = 1
SET #TableName = 'Tbl_Lube'
SET #SQL_ExtractDlSql = 'SELECT Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=#AreaID AND TableName=#TableName'
SET #ParameterDefinition = '#AreaID INT,#DayPrior INT,#TableName VARCHAR(50)'
EXECUTE sp_executesql #SQL_ExtractDlSql,
#ParameterDefinition,
#AreaID,
#DayPrior,
#TableName
PRINT #SQL_ExtractDlSql
I above Stored procedure, I get What I wanted on print, but instead of doing that, I wanted the selected data stores as a variable.
Then what I done is I declared a variable #StoreSql and made some modified into the SQL statement show below:
Variable Declaration:
DECLARE #StoreSql AS NVARCHAR(MAX)
Modified the Code:
SET #SQL_ExtractDlSql = 'SELECT #StoreSql = Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=#AreaID AND TableName=#TableName'
I executed the code, I get error Must declare the scalar variable "#StoreSql".
I have totally no idea how to deal with this.Any one can help.Beside,I am new to sqlserver,new to stored procedures.
Please don't hesitate to point out my any mistake,any..such as logic or etc. I learn from mistake.
Regards
LiangCk
The dynamic SQL string cannot reference variables from the outer scope. You need to declare it as an output parameter
SET #ParameterDefinition = '#AreaID INT,
#DayPrior INT,
#TableName VARCHAR(50),
#StoreSql NVARCHAR(MAX) OUTPUT'
EXECUTE sp_executesql #SQL_ExtractDlSql,
#ParameterDefinition,
#AreaID,
#DayPrior,
#TableName,
#StoreSql OUTPUT