SQL Server Invalid Column Name and String Value - sql

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.

Related

i get an uppercased table name calling a variable

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.

why I need a dynamic query for "column value from a query"

For example this returns a value from a query, which I will then use as a column name.
#A=Select top 1 productid from productlist order by timestamp desc
then I would like this "productid" A to be used in the other table
Select #A from customerlist
then the result is #A value instead of field value in customerlist.
When I use dynamic query, I can get right result.
Why?
(I know I can use join but because this productlist table is dynamic, so let's assume it is a sub query)
You need "dynamic SQL" because SQL will NOT allow you to use a parameter as a column name or a table name. You can only use parameters for data values such as in a where clause where column1 = #val
set #A = 'çolumn1'
Select #A from customerlist -- this fails because it is not allowed
Dynamic SQL is a "hack" to get around those restrictions as the SQL statement is placed into a string along with any value held by parameters.
set #A = 'çolumn1'
set #SQL = 'Select ' + #A + ' from customerlist;'
execute #SQL -- this works, the SQL statement is valid with no parameters as column names
The string formed as #SQL is a complete sql statement without needing any parameters as column names.
Note: the syntax I used here is incomplete and is based on MS SQL Server, different databases will use a different, but similar, syntax.

Trouble Getting Columns Names to Variable in SSIS Execute SQL Task

I'm attempting to validate some column headings before the import of a monthly data set. I've set up an Execute SQL Task that's supposed to retrieve the column headings of the prior month's table and store it in Header_Row as a single string with the field names separated by commas. The query runs just fine in SQL Server, but when running in SSIS, it throws the following error:
"The type of the value (Empty) being assigned to variable 'User:Header_Row' differs from the current variable type (String)."
1) Does this mean that I'm not getting anything back from my query?
2) Is there another method I should be using in SSIS to get the query results I'm looking for?
3) Is there an issue with me using the variable reference in my query as a portion of a string? I think the answer is yes, but would like to confirm, as my variable was still empty after changing this.
Original Query:
SELECT DISTINCT
STUFF((
SELECT
',' + COLUMN_NAME
FROM
db_Analytics.INFORMATION_SCHEMA.COLUMNS aa
WHERE
TABLE_NAME = 'dt_table_?'
ORDER BY
aa.ORDINAL_POSITION
FOR
XML PATH('')
), 1, 1, '') AS Fields
FROM
db_Analytics.INFORMATION_SCHEMA.COLUMNS a;
EDIT: After changing the variable to cover the full table name, I have a new error saying "The value type (__ComObject) can only be converted to variables of the type Object."
Final Query:
SELECT DISTINCT
CAST(STUFF((
SELECT
',' + COLUMN_NAME
FROM
db_Analytics.INFORMATION_SCHEMA.COLUMNS aa
WHERE
TABLE_NAME = ?
ORDER BY
aa.ORDINAL_POSITION
FOR
XML PATH('')
), 1, 1, '') As varchar(8000)) AS Fields
FROM
db_Analytics.INFORMATION_SCHEMA.COLUMNS a;
You are attempting to parameterize your query. Proper query parameterization is useful for avoiding SQL Injection attacks and the like.
Your query is looking for a TABLE_NAME that is literally 'dt_table_?' That's probably not what you want.
For laziness, I'd just rewrite it as
DECLARE #tname sysname = 'dt_table_' + ?;
SELECT DISTINCT
STUFF((
SELECT
',' + COLUMN_NAME
FROM
db_Analytics.INFORMATION_SCHEMA.COLUMNS aa
WHERE
TABLE_NAME = #tname
ORDER BY
aa.ORDINAL_POSITION
FOR
XML PATH('')
), 1, 1, '') AS Fields
FROM
db_Analytics.INFORMATION_SCHEMA.COLUMNS a;
If that's not working, you might need to use an Expression to build out the query.
I'm really pretty sure that this is your problem:
TABLE_NAME = 'dt_table_?'
I'm guessing this is an attempt to parameterize the query, but having the question mark inside the single-quote will cause the question mark to be taken literally.
Try like this instead:
TABLE_NAME = ?
And when you populate the variable that you use as the parameter value, include the 'dt_table_' part in the value of the variable.
EDIT:
Also in your ResultSet assignment, try changing "Fields" to "0" in the Result Name column.
There are two issues with the query above:
1) The query in the task was not properly parameterized. I fixed this by putting the full name of the prior month's table into the variable.
2) The default length of the result was MAX, which was causing an issue when SSIS would try to put it into my variable, Header_Row. I fixed this by casting the result of the query as varchar(8000).
Thanks for the help everyone.

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

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)