SQL query with column name obtained from another table SQL Server 2012 - sql

trying to run the query
select * from customers, TablesList where TablesList.TableName+'ID' =
10 and tableslist.tableid= 123
where the column name obtained from another table. I get the following error
Msg 245, Level 16, State 1, Line 1 Conversion failed when converting
the nvarchar value 'CustomersID' to data type int.
I know I can do something like Select * from customers where customersID = 10
But trying to create CustomersID column name dynamically from another table. The intent it to have TablesList.TableName+'ID' give me CustomersID string that I can use to equate to 10.

My guess is that the value for Tablelist.TableName is Customer so when you do + 'ID' it results in 'CustomerID'. 'CustomerID' is the VALUE that is returned and not the FIELD NAME that gets compared to 10.
Hence when sqlserver try to convert 'CustomerID' to 10 you get an error message telling you that it's not an integer Value.
As far as I know you cannot get a "field name" from a field value directly trough SQL, for that you'd need to create a stored proc or some kind of programming language to build the query dynamically

TablesList.TableName+'ID' generates the string 'CustomersID'. You get the error because your comparison is actually made like this:
'CustomersID' = 10 -- The comparison NVARCHAR = INT produces the error
What i think you're trying to achieve requires dynamic SQL.

The problem with what you have is that your where clause is checking if the value 'CustomerID' is equal to 10. It isn't (and can't) use that string as a column name in that context. You need to use dynamic sql.
Dynamic SQL is where you build up a string which contains the SQL you ulitmately want to run. So as an example, you could do something like this:
declare #sql varchar(max)
set #sql = 'select * from customers where ' + (select top 1 TableName from TableList where tableId = 123) + 'ID = 10'
EXEC(#sql)
This sets the #sql variable to select * from customers where customerID = 10 then runs that statement.

Use Concat:
select * from customers, TablesList where Concat('TablesList.TableName','ID') =
10 and tableslist.tableid= 123

Related

Anything like template literals while writing a search query in SQL?

I am writing a stored procedure to get a particular value.
declare #num int
set #num = (SELECT Id
FROM [sometable]
WHERE Name like '%today%')
-- returns #num = 1
Select Value
FROM [anothertable]
where name like 'days1'
In the last line of the query I want to add "1" or any other number after 'days', depending on the variable #num.
How can I do it, sort of like how we use template literals in Javascript, using the ${} syntax but in SQL?
You can just use the first query as a sub-query of the second:
select [Value]
from anothertable
where [name] = Concat('days', (select Id from sometable where [Name] like '%today%'));

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.

return value that column value found matched with the variables value in MSSQL

I have the following SQL script use to select the records that current_status contains the following variables #isPending, #isInvoiced, #isRework, #isCancelled.
SELECT *
FROM vw_sale_search vss
WHERE CONTAINS (( #isPending, #isInvoiced, #isRework, #isCancelled), vss.current_status )
However, error message is:
(Incorrect syntax near '#isPending'.)
display when I tried to run the script.
The main container, in this case your current_status column should be placed in the first place. Then the item to be searched will take the second place in SQL Server Full-Text CONTAINS function
To searching for more than one word, you can use OR syntax in the CONTAINS function
I created sample fulltext catalog and text table as shown in SQL Fulltext tutorial and prepared fıllowing SQL Select script to use OR with Contains function
declare #isPending varchar(10) = 'Data', #isInvoiced varchar(10) = 'Pool', #txt varchar(100)
set #txt = #isPending + ' OR ' + #isInvoiced
SELECT * FROM TextTable WHERE CONTAINS (textColumn, #txt)

SQL Server 2005 I am not able to read from a table

Please suppose that in SQL Server 2005, if you launch the following query:
SELECT CHICKEN_CODE FROM ALL_CHICKENS WHERE MY_PARAMETER = 'N123123123';
you obtain:
31
as result.
Now, I would like to write a function that, given a value for MY_PARAMETER, yields the corresponding value of CHICKEN_CODE, found in the table ALL_CHICKENS.
I have written the following stored function in SQL Server 2005:
ALTER FUNCTION [dbo].[determines_chicken_code]
(
#input_parameter VARCHAR
)
RETURNS varchar
AS
BEGIN
DECLARE #myresult varchar
SELECT #myresult = CHICKEN_CODE
FROM dbo.ALL_CHICKENS
WHERE MY_PARAMETER = #input_parameter
RETURN #myresult
END
But if I launch the following query:
SELECT DBO.determines_chicken_code('N123123123')
it yields:
NULL
Why?
Thank you in advance for your kind cooperation.
define the length of your varchar variables like this
varchar(100)
Without the 100 (or whatever length you choose) its lengh is 1 and the where clause will filter out the correct results.
Specify a length for your varchar (ex.: varchar(100)). Without length, varchar = 1 char.
As per other PS, You can store only one char in the #myresult because you have not specified any length, bcoz 1 char length is default for Varchar datatype.
Why we are getting NUll, not the first char:
If there are multiple records are filtered on basis of Where clause in ALL_CHICKENS table then the value of CHICKEN_CODE column is picked up from last row in ALL_CHICKENS table.
It seems that the last row has null value in CHICKEN_CODE column.
Specify a length for #input_parameter, #myresult as by default varchar lengh is 1.