Concatenating single quote in where clause to a variable in T-SQL - tsql

I have a VARCHAR variable declared which I want to use in a where clause to search results with a specific phone number.
DECLARE #Phone VARCHAR(50)
SET #Phone = 075000000
SELECT *
FROM my_table
WHERE phone = ''' + #Phone + '''
but it does not return any result. It works when I use WHERE phone = '075000000'
. I tried also WHERE phone = '''' + #Phone + '''' and WHERE phone = CHAR(39) + #Phone + CHAR(39) but still no results.
Also tried to declare #Phone as NUMERIC and converting it to string CONVERT(VARCHAR(50), #Phone) but still same issue.
phone column is a NVARCHAR(50), not null .

Can you try
DECLARE #Phone VARCHAR(50)
SET #Phone = '''075000000'''
SELECT *
FROM my_table
WHERE phone = #Phone

Please try the following:
DECLARE #Phone NVARCHAR(50)
SET #Phone = '075000000'
SELECT *
FROM my_table
WHERE phone = #Phone
#Stu has already provided the answer and the explanation in the comments section.

Related

The name "xxx" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables

I want to separate a table's columns into two set (1st set = bottom 50%, 2nd set = top 50%, there is a reason why I am not using a median formula in this case and I know that there will be a case when the count([ORDINAL_POSITION]) will be an odd number, then I won't get accurate result.) to achieve this I am trying to use INFORMATION_SCHEMA.COLUMNS, but I can't figure it out why I got the following error message:
The name "sometable" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
DECLARE #table2 NVARCHAR(MAX)
DECLARE #table_op_mid INT
SET #table2 = 'sometable'
SELECT #table_op_mid = 'SELECT ROUND(MAX([ORDINAL_POSITION])/2,0) AS OP FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '+#table2+''
PRINT (table_op_mid)
EXEC (#table_op_mid)
1st problem is that #table_op_mid is declared as INT instead of VARCHAR
2nd problem is that #table2 need extra quotes when used in TABLE_NAME comparision
3rd problem is that table_op_mid is missing # symbol, should be PRINT(#table_op_mid)
DECLARE #table2 NVARCHAR(MAX)
DECLARE #table_op_mid NVARCHAR(MAX)
SET #table2 = 'sometable'
SELECT #table_op_mid = 'SELECT ROUND(MAX([ORDINAL_POSITION])/2,0) AS OP FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '''+#table2+''''
PRINT (#table_op_mid)
EXEC (#table_op_mid)
EDIT
After your comment.. It is the same problem as before.. #SQL_columnnull_part_2 should be VARCHAR instead of INT
declare #db2 varchar(max) = 'MyDb'
declare #table2 varchar(max) = 'sometable'
declare #SQL_columnnull_part_2 varchar(max) = ''
Also, your new query will not work because STRING_AGG doesn't add last separator, so you should move the comparision term in the 1st parameter and keep in separator only the ';'
SELECT #SQL_columnnull_part_2 = STRING_AGG(
'UPDATE ' + #db2 + '.[dbo].' + #table2 + ' WITH (TABLOCK) SET ' + QUOTENAME(COLUMN_NAME,'['']') + ' = NULL WHERE ' + QUOTENAME(COLUMN_NAME,'['']') + ' = ''''',
'; '
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #table2
AND [ORDINAL_POSITION] > #table_op_mid

Variable = MAX() Causing Incorrect Syntax

Have the following SQL below which will be part of a larger SP. I'm receiving a syntax error and I'm assuming it's due to the selected variable #ColumnMM containing a MAX function when trying to be executed withing the string of the variable #SQL. For example, changing Line 25 (#Column1) to
SELECT #Column01 = 'abcd01' FROM MonthlySummary works just fine.
How do I best resolve this?
IF OBJECT_ID('New_Report', 'U') IS NOT NULL
DROP TABLE New_Report
;
CREATE TABLE New_Report (
Area NVARCHAR(255)
, Division NVARCHAR(255)
)
;
DECLARE #Column01 VARCHAR(6)
DECLARE #Column02 VARCHAR(6)
DECLARE #Column03 VARCHAR(6)
DECLARE #Column04 VARCHAR(6)
DECLARE #Column05 VARCHAR(6)
DECLARE #Column06 VARCHAR(6)
DECLARE #Column07 VARCHAR(6)
DECLARE #Column08 VARCHAR(6)
DECLARE #Column09 VARCHAR(6)
DECLARE #Column10 VARCHAR(6)
DECLARE #Column11 VARCHAR(6)
DECLARE #Column12 VARCHAR(6)
;
SELECT #Column01 = MAX(reporting_year)+'01' FROM MonthlySummary
SELECT #Column02 = MAX(reporting_year)+'02' FROM MonthlySummary
SELECT #Column03 = MAX(reporting_year)+'03' FROM MonthlySummary
SELECT #Column04 = MAX(reporting_year)+'04' FROM MonthlySummary
SELECT #Column05 = MAX(reporting_year)+'05' FROM MonthlySummary
SELECT #Column06 = MAX(reporting_year)+'06' FROM MonthlySummary
SELECT #Column07 = MAX(reporting_year)+'07' FROM MonthlySummary
SELECT #Column08 = MAX(reporting_year)+'08' FROM MonthlySummary
SELECT #Column09 = MAX(reporting_year)+'09' FROM MonthlySummary
SELECT #Column10 = MAX(reporting_year)+'10' FROM MonthlySummary
SELECT #Column11 = MAX(reporting_year)+'11' FROM MonthlySummary
SELECT #Column12 = MAX(reporting_year)+'12' FROM MonthlySummary
;
DECLARE #SQL NVARCHAR(MAX)
;
SET #SQL = 'ALTER TABLE New_Report ADD ' + #Column01 + ' VARCHAR(6)';
EXEC sys.sp_executesql #SQL;
AND FYI -- The result of SELECT MAX(reporting_year)+'01' FROM MonthlySummary would be 202001. reporting_year is a VARCHAR(4) in MonthlySummary although I know that doesn't matter after using an aggregate function on it.
Take a look at this link from the documentation:
https://learn.microsoft.com/en-us/sql/relational-databases/databases/database-identifiers?view=sql-server-ver15#rules-for-regular-identifiers
Basically, you can't use a digit character as the first character of a table name, column name, etc.
That aside, I also see a type mismatch problem. MAX(reporting_year) is a number, but '01', '02', etc are text, and so you need to cast to combine them together. Additionally, the code is unnecessarily repetitive, both in terms of how it's written and for the work it causes the server to do. There's no good need to run the same aggregation across the entire table multiple times.
DECLARE #MaxYear AS VARCHAR(4)
SELECT #MaxYear = CAST(MAX(reporting_year) As varchar(4)) FROM MonthlySummary
DECLARE #Column01 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'01')
DECLARE #Column02 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'02')
DECLARE #Column03 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'03')
DECLARE #Column04 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'04')
DECLARE #Column05 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'05')
DECLARE #Column06 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'06')
DECLARE #Column07 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'07')
DECLARE #Column08 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'08')
DECLARE #Column09 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'09')
DECLARE #Column10 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'10')
DECLARE #Column11 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'11')
DECLARE #Column12 VARCHAR(9) = QUOTENAME('_'+#MaxYear+'12')
Finally, as a matter of good practice I object to naming the columns like this. If you want pivoted data, that's fine, but then let your client tool worry about the names and adjust as needed. Do this, and it's likely you can significantly simplify this entire procedure, possibly down the point of a single SELECT statement.

Cannot execute user defined function UDF in SQL Server

I am creating a function to return the full name of a customer when a customer id is entered:
CREATE FUNCTION displayName
(
#customer_id int
)
RETURNS varchar(50)
AS
BEGIN
DECLARE #name varchar(50)
SELECT #name = (SELECT name_first + ' ' + name_last AS FULL_NAME FROM DT_CUSTOMERS WHERE customer_id = #customer_id)
RETURN #name
END
GO
Is something wrong with my code? How do I run it?
Common practice is to define in which DB you are going to run the query (you might be in the wrong db where you don't have any rights?) and which schema you want to add to it:
When executed like this, it should work.
USE
databasename_here
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION dbo.displayName
(
#customer_id int
)
RETURNS varchar(50)
AS
BEGIN
DECLARE #name varchar(50)
SELECT #name = (SELECT name_first + ' ' + name_last AS FULL_NAME FROM DT_CUSTOMERS WHERE customer_id = #customer_id)
RETURN #name
END
GO
It should be executed as follows:
SELECT
dbo.displayName(column_which_contains_id)
from db.schema.table
it doesn't work in my case without the user.
I had to type dbo.displayName

TSQL Replace Doubled Characters

Let's say I have data:
heloo
cuube
triniity
How to write script that will replace those "doubled" characters with only one? So the result from the above data set would be:
helo
cube
trinity
Usually I post some script where I tried to achieve this, but this time I can't think of any.
This should work:
CREATE PROCEDURE remove_duplicate_characters(#string VARCHAR(100))
AS
DECLARE #result VARCHAR(100)
SET #result=''
SELECT #result=#result+MIN(SUBSTRING(#string ,number,1)) FROM
(
SELECT number FROM master..spt_values WHERE type='p' AND number BETWEEN 1 AND len(#string )) AS t GROUP BY SUBSTRING(#string,number,1) ORDER BY MIN(number)
)
SELECT #result
GO
You then call it like this:
EXEC remove_duplicate_characters 'heloo'
Source
This script does not depend on having access to master functions, and just relies on t-sql string functions.
declare #word varchar(100) = 'aaaacuuuuuubeeeee', #result varchar(100) = ''
declare #letter char, #idx int = 0, #lastletter char = ''
while(#idx <= len(#word))
begin
select #letter = substring(#word,#idx,1)
if (#letter != #lastletter)
begin
select #result = concat(#result,#letter)
end
select #lastletter = #letter,#idx = #idx + 1
end
select #result

Am I allowed to declare wildcards for LIKE operators prior to their use in the clause?

Just for tidyness purposes, I would like to declare the scalar values of search parameters in a stored procedure of mine (for SQL Server 2012), prior to actually using them in the WHERE clause of my search. So basically I would like to do this:
CREATE PROCEDURE [test_select]
#firstName VARCHAR(50)
, #lastName VARCHAR(50)
AS
IF #firstName != ''
BEGIN
SET #firstName = '%' + #firstName + '%'
END
IF #lastName != ''
BEGIN
SET #lastName = '%' + #lastName + '%'
END
SELECT *
FROM [dbo].[Member] AS Member
WHERE
( #firstName != '' AND #firstName LIKE [Member].[FirstName] )
OR ( #lastName != '' AND #lastName LIKE [Member].[LastName] )
I'm still somewhat new to SQL, so my question is simple, is what I'm trying to do here going to insert the wildcards like I expect for use in the LIKE operator?
Yes Like takes a string.
Declare #LikeString nvarchar(max) = '%Name%'
Select *
From table
Where Column Like #LikeString