How to set into query string the Replace Statement in SQL? - mysql

This is my problem.. but i will show example to make it simpler
I have a stored proc named usp_Replace. This sp will replace quotation marks with whitespace.
This is the original query without setting it into query string..
CREATE PROCEDURE usp_Replace
#desc varchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT '' + Replace(REPLACE(REPLACE(#desc, CHAR(13), ''), CHAR(10), ''),'"','') + ''
END
but..
I want to set the select statement into query string because for some reason I will have to use condition statement but will not show it as it is not part of the problem.
Here..
ALTER PROCEDURE usp_Replace
#desc varchar(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #query nvarchar(max)
DECLARE #condition nvarchar(max)
SET #condition = null
SET #query = ' SELECT '' + Replace(REPLACE(REPLACE('''+#desc+''', CHAR(13), ''), CHAR(10), ''),''"'','') + '' '
SET #query = #query + ISNULL(#condition,'')
EXEC sp_executesql #query
END
I'm getting error on this, resulting that there is unclosed quotation marks.
I'm really having problem with how and where to put single quotation marks.
Please help, if you have encountered this problem or any links/suggestions. I will be glad to learn about it. Thanks.

You need to quote all the single in the string, including the empty string. So, '' becomes '''':
SET #query = 'SELECT Replace(REPLACE(REPLACE(#desc, CHAR(13), ''''), CHAR(10), ''''),'' " '', '''') '
I'm not sure what the empty strings were doing at the beginning and end, so I just removed them.

Related

How to not show certain columns in MySQL? [duplicate]

when I do:
SELECT *
FROM SOMETABLE
I get all the columns from SOMETABLE, but I DON'T want the columns which are NULL (for all records). How do I do this?
Reason: this table has 20 columns, 10 of these are set but 10 of them are null for certain queries. And it is time consuming to type the columnnames....
Thanks,
Voodoo
SQL supports the * wildcard which means all columns. There is no wildcard for all columns except the ones you don't want.
Type out the column names. It can't be more work than asking questions on Stack Overflow. Also, copy & paste is your friend.
Another suggestion is to define a view that selects the columns you want, and then subsequently you can select * from the view any time you want.
It's possible to do, but kind of complicated. You can retrieve the list of columns in a table from INFORMATION_SCHEMA.COLUMNS. For each column, you can run a query to see if any non-null row exists. Finally, you can run a query based on the resulting column list.
Here's one way to do that, with a cursor:
declare #table_name varchar(256)
set #table_name = 'Airports'
declare #rc int
declare #query nvarchar(max)
declare #column_list varchar(256)
declare columns cursor local for select column_name
from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = #table_name
open columns
declare #column_name varchar(256)
fetch next from columns into #column_name
while ##FETCH_STATUS = 0
begin
set #query = 'select #rc = count(*) from ' + #table_name + ' where ' +
#column_name + ' is not null'
exec sp_executesql #query = #query, #params = N'#rc int output',
#rc = #rc output
if #rc > 0
set #column_list = case when #column_list is null then '' else
#column_list + ', ' end + #column_name
fetch next from columns into #column_name
end
close columns
deallocate columns
set #query = 'select ' + #column_list + ' from ' + #table_name
exec sp_executesql #query = #query
This runs on SQL Server. It might be close enough for Sybase. Hopefully, this demonstrates that typing out a column list isn't that bad :-)

how to write procedure to add where clause dynamically in mysql

I want to write the store procedure in mysql where I want to add "where clause"
dynamically
I have written the Sp but Its Giving an error
Please Help
CREATE PROCEDURE GetStudent(
#Center varchar(20)=null,
#Gender varchar(20) = null,
#yrOf10 date= null,
#Designation varchar(20)= null,)
AS DECLARE #Query VARCHAR(100);DECLARE #ParamDefinition NVARCHAR(2000);
SET #Query = ' SELECT * FROM Student WHERE 1=1';IF #Center IS NOT NULL
SET #Query = #Query + ' AND Center= #Center ';IF #Gender IS NOT NULL SET #Query = #Query + ' AND Gender=#Gender ';IF #yrOf10 IS NOT NULL SET #Query = #Query + ' AND yrOfPassing10=#yrOf10 ';IF #Designation IS NOT NULL SET #Query = #Query + ' AND Designation=#Designation';
You can not use the # sign in an object name http://dev.mysql.com/doc/refman/5.0/en/identifiers.html.
I don't know why you have prefixed everything with #. Did you start out with MS SQL or something?
Anyway to decalre a local var you use DECLARE http://dev.mysql.com/doc/refman/5.0/en/declare-local-variable.html

Cast in SQL Server query

I am having a problem with executing one SQL query, Below is my stored procedure
Query
ALTER PROCEDURE ProcName
(
#iID VARCHAR(50),
#AccountID INT
)
AS
SET NOCOUNT ON
DECLARE #Sql VARCHAR(MAX)
SET #Sql = 'DELETE FROM ReferringPhysician WHERE iID IN(' + #iID + ') AND AccountID = '+ #AccountID + ''
EXEC (#Sql)
I am trying to execute this query but it gives me error because i am using exec(), Here in my where condition i am dealing with the string, and in another condition i am dealing with the int, so in second condition i am getting casting error! how can i get through this?
Any help is greatly Appreciated!
Thanks
Your query is susceptible to SQL injection.
One way to avoid the data type problem you are having is to pass proper data types where you can and not use EXEC() (more details here):
DECLARE #sql NVARCHAR(MAX) = N'DELETE dbo.referringPhysician
WHERE iID IN (' + #iID + ') AND AccountID = #AccountID;';
EXEC sp_executesql #sql, N'#AccountID INT', #AccountID;
You can completely protect this from SQL injection by using table-valued parameters and passing in a DataTable or other collection with proper types instead of a comma-delimited string. e.g.:
CREATE TYPE dbo.iIDs TABLE(iID INT PRIMARY KEY);
Now your stored procedure can avoid dynamic SQL altogether:
ALTER PROCEDURE dbo.ProcName -- always use schema prefix!
#iIDs dbo.iIDs READONLY,
#AccountID INT
AS
BEGIN
SET NOCOUNT ON;
DELETE r
FROM dbo.ReferringPhysician AS r
INNER JOIN #iIDs AS i
ON r.iID = i.iID
WHERE r.AccountID = #AccountID;
END
GO
Try this:
ALTER PROCEDURE ProcName
(
#iID VARCHAR(50),
#AccountID INT
)
AS
SET NOCOUNT ON
DECLARE #Sql VARCHAR(MAX)
SET #Sql = 'DELETE FROM ReferringPhysician WHERE iID IN(' + CAST(#iID AS VARCHAR) + ') AND AccountID = '+ CAST(#AccountID AS VARCHAR) + ''
EXEC (#Sql)

SQL SERVER how to escape special character

I have a table that exists on a linked server and it has a field called name and I want to search a string called Macy's on that field. I am executing this as a dynamic SQL:-
declare #Sql nvarchar(2000)
declare #searchName nvarchar(255)
SET #searchName = N'macy''s'
SET #sql = 'SELECT * from crm_opportunity o where o.NAME LIKE ''% ' + #searchName + '%'' ESCAPE '''''' '
exec (#sql).
In other words I am trying to escape the single quote. I get the error Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 's'.
Any ideas and suggestions!
Instead of using EXEC, use sp_executesql and parameterize your query:
execute sp_executesql
N'SELECT * from crm_opportunity o where o.NAME LIKE ''%'' + #searchName + ''%''',
N'#searchName nvarchar(255)',
#searchName = N'macy''s'
Not only does this help avoid confusing quote escaping, but it also protects you against Sql Injection attacks.
Doubling quotes escapes the character so you use it inside a string value.
exec('select * from [dbo].[UsersTbl] where and UserType = ''CLT'' ')

copy entire row (without knowing field names)

Using SQL Server 2008, I would like to duplicate one row of a table, without knowing the field names. My key issue: as the table grows and mutates over time, I would like this copy-script to keep working, without me having to write out 30+ ever-changing fields, ugh.
Also at issue, of course, is IDENTITY fields cannot be copied.
My code below does work, but I wonder if there's a more appropriate method than my thrown-together text string SQL statement?
So thank you in advance. Here's my (yes, working) code - I welcome suggestions on improving it.
Todd
alter procedure spEventCopy
#EventID int
as
begin
-- VARS...
declare #SQL varchar(8000)
-- LIST ALL FIELDS (*EXCLUDE* IDENTITY FIELDS).
-- USE [BRACKETS] FOR ANY SILLY FIELD-NAMES WITH SPACES, OR RESERVED WORDS...
select #SQL = coalesce(#SQL + ', ', '') + '[' + column_name + ']'
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'EventsTable'
and COLUMNPROPERTY(OBJECT_ID('EventsTable'), COLUMN_NAME, 'IsIdentity') = 0
-- FINISH SQL COPY STATEMENT...
set #SQL = 'insert into EventsTable '
+ ' select ' + #SQL
+ ' from EventsTable '
+ ' where EventID = ' + ltrim(str(#EventID))
-- COPY ROW...
exec(#SQL)
-- REMEMBER NEW ID...
set #EventID = ##IDENTITY
-- (do other stuff here)
-- DONE...
-- JUST FOR KICKS, RETURN THE SQL STATEMENT SO I CAN REVIEW IT IF I WISH...
select EventID = #EventID, SQL = #SQL
end
No, there isn't any magic way to say "SELECT all columns except <foo>" - the way you're doing it is how you'll have to do it (the hack in the other answer aside).
Here is how I would alter your code, with these changes (some are hyperlinked so you can read my opinion about why):
use sys.columns over INFORMATION_SCHEMA.COLUMNS
use nvarchar instead of varchar
use scope_identity instead of ##identity
use sp_executesql instead of exec
use stuff instead of coalesce
use SET NOCOUNT ON
add semi-colons
use the schema prefix
use QUOTENAME since it's safer than '[' + ... + ']'
ALTER PROCEDURE dbo.spEventCopy
#EventID INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX) = N'';
SELECT #sql += ',' + QUOTENAME(name)
FROM sys.columns
WHERE [object_id] = OBJECT_ID('dbo.EventsTable')
AND is_identity = 0;
SET #sql = STUFF(#sql, 1, 1, '');
SET #sql = N'INSERT dbo.EventsTable(' + #sql + ')
SELECT ' + #sql + ' FROM dbo.EventsTable
WHERE EventID = ' + CONVERT(VARCHAR(12), #EventID) + ';';
EXEC sp_executesql #sql;
SELECT #EventID = SCOPE_IDENTITY();
-- do stuff with the new row here
SELECT EventID = #EventID, SQL = #SQL;
END
If you know the what your identity column is called (and it won't be the column changing), you could do this:
SELECT * INTO #dummy FROM EventsTable where EventID = #EventID;
ALTER TABLE #dummy
DROP COLUMN MyIdentityColumn
INSERT EventsTable SELECT * FROM #dummy
DROP TABLE #dummy
Since a table can only every have one identity column, specifying that in the query shouldn't limit you too much.
As Aaron Bertrand points out, there are risks associated with this approach. Please read the discussion in the comments below.