i get an uppercased table name calling a variable - sql

I set a variable name for a table as lowercase:
Set TGT_TABLE = 'tab_name';
however when i try to call it:
select * from table($TGT_TABLE);
I get an error:
SQL compilation error: Object 'TAB_NAME' does not exist or not authorized.
Why is it calling the uppercase version of my table name
Also I veriefied in the 'show variables' that my variable is indeed lowercase

in order to use lower case identifiers, these must be in double-quotes. in order to assign it to a variable, this must additionally be in single quotes.
#jarlh 's answer is correct, note the single quotes surrounding the double quotes.
Set TGT_TABLE = '"tab_name"';
select * from table($TGT_TABLE);
if in doubt, copy/ paste

You can Write Your Code Like This :
declare #TGT_TABLE nvarchar(50),#query nvarchar(50)
Set #TGT_TABLE = 'name of your table';
SET #query = 'SELECT * FROM ' + #TGT_TABLE;
EXEC(#query);
It will worked.

Related

SQL Server Invalid Column Name and String Value

I have the following code snippet from a SQL Server Stored Procedure.
DECLARE #sql nvarchar(Max)
SET #sql = N'
WITH CTE AS
(
SELECT * FROM #TEMP WHERE ...
),
Track AS
(
SELECT *,
CASE WHEN 1B1 = "Track" AND (QTRK_1B1 = "2D QT" OR QTRK_1B1 = "3D QT") THEN "Yes" ELSE "No" END AS Tracking
FROM CTE
),
... '
Exec sp_executesql #sql, N'#AirTarget nvarchar(25), #GroundTracker nvarchar(25)', #AirTarget, #GroundTracker
I am not sure what I am doing wrong here. When I execute the stored procedure, I am getting errors like:
Invalid Column Name 'Track'
Invalid Column Name '2D QT'
Invalid Column Name '3D QT'
Invalid Column Name 'Yes'
Invalid Column Name 'No'
But those are not column names from the table. I have Googled and cannot figure out what I am doing wrong.
I have tried surrounding those values with single quotes, and I have tried removing the quotes from around those values and nothing works. Any help would be appreciated
SQL use single quote ' for string
CASE
WHEN 1B1 = ''Track'' AND (QTRK_1B1 = ''2D QT'' OR QTRK_1B1 = ''3D QT'') THEN ''Yes''
ELSE ''No''
END AS Tracking
They all definitely should be single quotes - all places where you have double-quotes. If
you do that it should at least give you a different message.
You'll also need to wrap 1B1 in square brackets like [1B1] as it won't like a column name starting with a number in a CASE statement.

Setting a character variable which consists of this (') character

I want to set a variable to expressions like this 'word' in SQL which consists of this (') character.
How can I do that?
For SQL Server to show ' use '' into select
SELECT 'aa''a'
You can use variable with Single quotes as following :-
DECLARE #varName VARCHAR(50)
SET #varName = '''word'''
SELECT #varName as colName
Output :- 'word'
Sample Fiddle

Create INSERT statement using parameter

I need to create a INSERT statement using parameters. Say I have two variable name #DestinationFields, #InsertValues.
Here #DestinationFields contain the column name like: product,price and #InsertValues contains the values for those two columns, like: Book,100.
Now, How i create a insert command to insert those values where each value need to add a quotation mark .I already tried as
I already tried as
EXEC('INSERT into tbl_test('+#DestinationFields+')values('+#InsertValues+')')
But it's returning an error.
The name "book" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some
contexts) variables. Column names are not permitted.
How do I do it? Thanks in advance.
Pretending there is no problem of SQL injection here*, you can quickly fix your code by adding quotation marks around Book. The value of # InsertValues should be
'Book', 100
instead of simply
Book, 100
You need to add quotation marks around each string value; otherwise, strings are interpreted as names, which is not valid.
EDIT : (in response to a comment) If all columns are of varchar type, you can put quotes around the entire string, and replace all commas with the quote-comma-quote pattern, like this:
values('''+REPLACE(#InsertValues,',',''',''')+''')'
* You should not put code like this into production, because it can be manipulated to harm your system rather severely. Here is a good illustration of the problem (link).
Try:
DECLARE #DestinationFields VARCHAR(200);
SET #DestinationFields = 'Col1, Col2, Col3'
DECLARE #InsertValues VARCHAR(200);
SET #InsertValues = '1, 2, 3'
DECLARE #SQLString VARCHAR(1000);
SET #SQLString = 'INSERT INTO tbl_test (' + #DestinationFields + ') VALUES (' + #InsertValues + ')';
EXEC (#SQLString)
However, this is very open to SQL Injection attacks. But, it will do what you require.
The Curse and Blessing of Dynamic SQL

How to include double quotes in select statement?

i have a table like
id name
10 bob
20 bill
i want to select only name column in output with double quotes
like select '"'||name||'"' from table
it is giving me the correct output but is there any other way without using concatenation ...
Thank you..
Using this you can get result with double quotes
' " ' + columnName + ' " '
Example
Query
SELECT '"'+Name+'"' , Age
FROM customer
Result
"Viranja" | 27
Create a virtual column that adds the quotes:
CREATE TABLE
....
quoted_name VARCHAR2 GENERATED ALWAYS AS ('"' || name || '"') VIRTUAL,
...
See here for more information:
http://www.oracle-base.com/articles/11g/virtual-columns-11gr1.php
this will check for any name with at least one double quote
select * from table
where name like '%"%'
If your intention is to be able to "export" the result into space or comma-delimited text file, use a view to "format" your data. You will need to this for your date columns as well.
There are two scenarios you would want to use double quotes in sql in my opinion.
Updating a string column which contains single multiple quotes in it. (you have to escape it)
updating blog contents in columns which you cant edit in "edit top 200 rows"
so, if you want to use double quotes follow this.
SET QUOTED_IDENTIFIER OFF
BEGIN
DECLARE #YourSqlStmt AS VarChar(5000) -- Declare a variable.
SET #YourSqlStmt = "ok"
PRINT #YourSqlStmt -- do your operations here
END
This saves time and you need not to escape single quotes in a existing string content of the column.

SQL Server Fulltext Search contains phrase problem

I have a problem with SQL Server 2008 full text search I have the following query
SELECT *
FROM cigars
WHERE CONTAINS(cigars.*, #Search )
#Search is a value that is passed in through a stored procedure. But, thats not the problem.
What is is if someone searches for say 'Punch' it works fine and I get all cigars that match.
Where the problem lays is if they search for 'Punch Cigar' I get this error.
Syntax error near 'Cigar' in the full-text search condition 'Punch Cigar'.
Any idea on how I can get it to allow for it to search for that phrase?
Why are you searching by all columns in the CIGAR table? Surely some of them do not use a string/text based data type...
After looking at the CONTAINS documentation, I'd look at a function to properly escape the words for the FTS searching:
CREATE FUNCTION [dbo].[escapeFTSSearch] (
#SearchParameter NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
-- Declare the return variable here
DECLARE #result NVARCHAR(MAX)
SELECT #result = '"'+ REPLACE(REPLACE(#SearchParameter,'"',''), ' ', '" AND "') +'"'
-- Return the result of the function
RETURN #result
END
Test:
SELECT [example].[dbo].[escapeFTSSearch] ('Punch Cigar')
...which gives me:
"Punch" AND "Cigar"
Usage:
WHERE CONTAINS(cigars.*, dbo.escapeFTSSearch(#Search) )
Addendum
The function is simplistic:
it assumes you want all words provided
doesn't support fuzzy searching
assumes double quotes aren't in the parameter value
Tweak as needed.
You need to ensure you have leading and trailing double quotes ans spaces. i.e. the value of #Search should be ' "Punch Cigar" '
Further to OMG's comments about escaping you would definitely need to strip out any embedded double quotes.
declare #Search varchar(1000)
set #Search = 'punch and" cigar'
set #Search = ' "' + REPLACE(#Search,'"','') + '" '
select * from sys.dm_fts_parser(#Search,1033,null,0)