I have a table with text field. I want to select rows where text is in all caps. This code works as it should, and returns ABC:
SELECT txt
FROM (SELECT 'ABC' AS txt UNION SELECT 'cdf') t
WHERE
txt COLLATE SQL_Latin1_General_CP1_CS_AS = UPPER(txt)
then I create UDF (as suggested here):
CREATE FUNCTION [dbo].[fnsConvert]
(
#p NVARCHAR(2000) ,
#c NVARCHAR(2000)
)
RETURNS NVARCHAR(2000)
AS
BEGIN
IF ( #c = 'SQL_Latin1_General_CP1_CS_AS' )
SET #p = #p COLLATE SQL_Latin1_General_CP1_CS_AS
RETURN #p
END
and run it as follows (which looks like an equivalent code to me):
SELECT txt
FROM (SELECT 'ABC' AS txt UNION SELECT 'cdf') t
WHERE
dbo.fnsConvert(txt, 'SQL_Latin1_General_CP1_CS_AS') = UPPER(txt)
however, this returns ABC as well as cdf.
Why is that so, and how do I get this to work?
PS I need UDF here to be able to call case-sensitive comparison from .Net LINQ2SQL provider.
A variable cannot have it's own collation. It will always use the server's default. Check this:
--I declare three variables, each of which get's its own collation - at least one might think so:
DECLARE #deflt VARCHAR(100) = 'aBc'; --Latin1_General_CI_AS in my system
DECLARE #Arab VARCHAR(100) = 'aBc' COLLATE Arabic_100_CS_AS_WS_SC;
DECLARE #Rom VARCHAR(100) = 'aBc' COLLATE Romanian_CI_AI
--Now check this. All three variables are seen as the system's default collation:
SELECT [name], system_type_name, collation_name
FROM sys.dm_exec_describe_first_result_set(N'SELECT #deflt AS Deflt, #Arab AS Arab, #Rom AS Rom'
,N'#deflt varchar(100), #Arab varchar(100),#Rom varchar(100)'
,0);
/*
name system_type_name collation_name
Deflt varchar(100) Latin1_General_CI_AS
Arab varchar(100) Latin1_General_CI_AS
Rom varchar(100) Latin1_General_CI_AS
*/
--Now we check a simple comparison of "aBc" against "ABC"
SELECT CASE WHEN #deflt = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckDefault
,CASE WHEN #Arab = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckArab
,CASE WHEN #Rom = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckRom
/*CI CI CI*/
--But we can specify the collation for one given action!
SELECT CASE WHEN #deflt = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckDefault
,CASE WHEN #Arab = 'ABC' COLLATE Arabic_100_CS_AS_WS_SC THEN 'CI' ELSE 'CS' END AS CheckArab
,CASE WHEN #Rom = 'ABC' COLLATE Romanian_CI_AI THEN 'CI' ELSE 'CS' END AS CheckRom
/*CI CS CI*/
--But a table's column will behave differently:
CREATE TABLE #tempTable(deflt VARCHAR(100)
,Arab VARCHAR(100) COLLATE Arabic_100_CS_AS_WS_SC
,Rom VARCHAR(100) COLLATE Romanian_CI_AI);
INSERT INTO #tempTable(deflt,Arab,Rom) VALUES('aBc','aBc','aBc');
SELECT [name], system_type_name, collation_name
FROM sys.dm_exec_describe_first_result_set(N'SELECT * FROM #tempTable',NULL,0);
DROP TABLE #tempTable;
/*
name system_type_name collation_name
deflt varchar(100) Latin1_General_CI_AS
Arab varchar(100) Arabic_100_CS_AS_WS_SC
Rom varchar(100) Romanian_CI_AI
*/
--This applys for declared table variables also. The comparison "knows" the specified collation:
DECLARE #TableVariable TABLE(deflt VARCHAR(100)
,Arab VARCHAR(100) COLLATE Arabic_100_CS_AS_WS_SC
,Rom VARCHAR(100) COLLATE Romanian_CI_AI);
INSERT INTO #TableVariable(deflt,Arab,Rom) VALUES('aBc','aBc','aBc');
SELECT CASE WHEN tv.deflt = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckDefault
,CASE WHEN tv.Arab = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckArab
,CASE WHEN tv.Rom = 'ABC' THEN 'CI' ELSE 'CS' END AS CheckRom
FROM #TableVariable AS tv
/*CI CS CI*/
UPDATE Some documentation
At this link You can read about the details. A collation does not change the value. It applys a rule (related to NOT NULL which does not change the values, but just adds the rule whether NULL can be set or not).
The documentation tells clearly
Is a clause that can be applied to a database definition or a column definition to define the collation, or to a character string expression to apply a collation cast.
And a bit later you'll find
Creating or altering a database
Creating or altering a table column
Casting the collation of an expression
UPDATE 2: A suggestion for a solution
If you want to have control whether a comparison is done CS or CI you might try this:
DECLARE #tbl TABLE(SomeValueInDefaultCollation VARCHAR(100));
INSERT INTO #tbl VALUES ('ABC'),('aBc');
DECLARE #CompareCaseSensitive BIT = 0;
DECLARE #SearchFor VARCHAR(100) = 'aBc';
SELECT *
FROM #tbl
WHERE (#CompareCaseSensitive=1 AND SomeValueInDefaultCollation=#SearchFor COLLATE Latin1_General_CS_AS)
OR (ISNULL(#CompareCaseSensitive,0)=0 AND SomeValueInDefaultCollation=#SearchFor COLLATE Latin1_General_CI_AS);
With #CompareCaseSensitive set to 1 it will return just the aBc, with NULL or 0 it will return both lines.
This is - for sure! - much better in performance than an UDF.
Please try using BINARY_CHECKSUM Function, and no need to UDF Function:
SELECT txt
FROM (SELECT 'ABC' AS txt UNION SELECT 'cdf') t
WHERE
BINARY_CHECKSUM(txt)= BINARY_CHECKSUM(UPPER(txt))
I think you are confused on how collation works. If you want to force a case sensitive collation you would do it in your where predicate, not with a function like that. And scalar functions are horrible for performance.
Here is how you would be able to use collation for this type of thing.
SELECT txt
FROM (SELECT 'ABC' AS txt UNION SELECT 'cdf') t
WHERE txt collate SQL_Latin1_General_CP1_CS_AS = UPPER(txt)
Here's what I did:
I changed the function to perform a comparison, instead of setting the collation, and then return a 1 or 0.
CREATE FUNCTION [dbo].[fnsConvert]
(
#p NVARCHAR(2000) ,
#c NVARCHAR(2000)
)
RETURNS BIT
AS
BEGIN
DECLARE #result BIT
IF ( #c = 'SQL_Latin1_General_CP1_CS_AS' )
BEGIN
IF #p COLLATE SQL_Latin1_General_CP1_CS_AS = UPPER(#p)
SET #result = 1
ELSE
SET #result = 0
END
ELSE
SET #result = 0
RETURN #result
END
Then the query that uses the function changes just a bit.
SELECT txt
FROM (SELECT 'ABC' AS txt UNION SELECT 'cdf') t
WHERE
dbo.fnsConvert(txt, 'SQL_Latin1_General_CP1_CS_AS') = 1
As #Shnugo stated, the collation is not an attribute of a variable, but it can be attribute of a column definition.
For collation-enabled comparison outside of TSQL, you can define a (persisted) computed column with an explicit collation:
create table Q47890189 (
txt nvarchar(100),
colltxt as txt collate SQL_Latin1_General_CP1_CS_AS persisted
)
insert into Q47890189 (txt) values ('ABC')
insert into Q47890189 (txt) values ('cdf')
select * from Q47890189 where txt = UPPER(txt)
select * from Q47890189 where colltxt = UPPER(colltxt)
Note that a persisted column can also be indexed, and has a better performance than calling a scalar function.
COLLATE :Is a clause that can be applied to a database definition or a column definition to define the collation, or to a character string expression to apply a collation cast.
COLLATE do not convert any column or variable..It define the characteristics of collate.
CREATE TABLE [dbo].[OINV]
[CardCode] [nvarchar](50) NULL
)
if i have a table with 5175460 rows
then converting this to another data type will take time because its of its value is converted to new data type.
alter table OINV
alter column CardCode varchar(50)
--1 min 45 sec
alter table OINV
alter column CardCode nvarchar(50) COLLATE SQL_Latin1_General_CP1_CS_AS
If i don't convert the data type and only want to change collate
then it take 1 ms to do so.That means it do not convert 5175460 rows to said collate.
It just define the collate on that column.
when this column is use in where condition then column will exhibit characteristics of said collate.
UDF/TVF is not perform-ant way to do so.Best way is to alter table
Another example,
declare #i varchar(60)='ABC'
SELECT txt
FROM (SELECT 'abc' AS txt UNION SELECT 'cdf') t
WHERE
txt = #i COLLATE SQL_Latin1_General_CP1_CS_AS
I can't declare it like this,
declare #i varchar(60) COLLATE SQL_Latin1_General_CP1_CS_AS='ABC'
So variable will exhibit collate characteristics only as long as it is use along collate .
In your case you are return only plain variable,
UDF way of doing so,
CREATE FUNCTION testfn (
#test VARCHAR(100)
,#i INT
)
RETURNS TABLE
AS
RETURN (
-- insert into #t values(#test)
SELECT #test COLLATE SQL_Latin1_General_CP1_CS_AS AS a
)
SELECT *
FROM (
SELECT 'ABC' AS txt
UNION
SELECT 'cdf'
) t
OUTER APPLY dbo.testfn(txt, 0) fn
WHERE fn.a = UPPER(txt)
To define multiple collate you have to define multiple table with different collate. TVF can return only static table schema,so there can be only one collate define.
Therefore TVF is not right way to perform your task.
I agree with #Shnugo when you create local variable it will take default collation
But, you could explicitly collate your variable values returned by function with your user defined collation as follow :
select * from
(SELECT 'ABC' AS txt UNION SELECT 'cdf') a
where (dbo.fnsConvert(txt, 'SQL_Latin1_General_CP1_CS_AS')
collate SQL_Latin1_General_CP1_CS_AS) = UPPER(txt)
In addition collate clause can only applied to database definition, column defination or string/character expression, in other words it is used for database objects i.e. tables, columns, indexes
collation_name can't be represented by variable or expression.
MSDN clearly defines COLLATE:
Is a clause that can be applied to a database definition or a column
definition to define the collation, or to a character string
expression to apply a collation cast.
Can you see a word about variable here?
If you need UDF, just use table-valued function:
CREATE FUNCTION dbo.test
(
#text nvarchar(max)
)
RETURNS TABLE
AS
RETURN
(
SELECT c COLLATE SQL_Latin1_General_CP1_CS_AS as txt
FROM (VALUES (#text)) as t(c)
)
GO
And use it like:
;WITH cte AS (
SELECT N'ABC' as txt
UNION
SELECT N'cdf'
)
SELECT c.txt
FROM cte c
OUTER APPLY dbo.test (c.txt) t
WHERE t.txt = UPPER(c.txt)
Output:
txt
------
ABC
Related
I want to select records from a table in a stored procedure. Given parameters can be empty or a string including some keys separated by comma (1, 2, etc)
I want to manage that when a parameter is an empty string, "WHERE" ignore searching.
I'm using this code:
where (CASE when #PatientID <> 0 then ( dental.ID_Sick in (1,2)) else (1=1) end)
Something like that is working in W3School. I mean:
SELECT * FROM Customers
WHERE (case when 1=1 then (Country IN ('Germany', 'France', 'UK')) else 1=1 end);
What is the problem in my query that does not work? SQLServerManagementStudio is giving error on "IN" statement.
Solution:
The best way to handle such optional parameters is to use dynamic SQL and built the query on the fly. Something like....
CREATE PROCEDURE myProc
#Param1 VARCHAR(100) = NULL
,#Param2 VARCHAR(100) = NULL
,#Param3 VARCHAR(100) = NULL
,#ListParam VARCHAR(100) = NULL
--, etc etc...
AS
BEGIN
SET NOCOUNT ON;
Declare #Sql NVARCHAR(MAX);
SET #Sql = N' SELECT *
FROM TableName
WHERE 1 = 1 '
-- add in where clause only if a value was passed to parameter
+ CASE WHEN #Param1 IS NOT NULL THEN
N' AND SomeColumn = #Param1 ' ELSE N'' END
-- add in where clause a different variable
-- only if a value was passed to different parameter
+ CASE WHEN #Param2 IS NOT NULL THEN
N' AND SomeOtherColumn = #Param3 ' ELSE N'' END
-- List Parameter used with IN clause if a value is passed
+ CASE WHEN #ListParam IS NOT NULL THEN
N' AND SomeOtherColumn IN (
SELECT Split.a.value(''.'', ''VARCHAR(100)'') IDs
FROM (
SELECT Cast (''<X>''
+ Replace(#ListParam, '','', ''</X><X>'')
+ ''</X>'' AS XML) AS Data
) AS t CROSS APPLY Data.nodes (''/X'') AS Split(a) '
ELSE N'' END
Exec sp_executesql #sql
, N' #Param1 VARCHAR(100), #Param2 VARCHAR(100) ,#Param3 VARCHAR(100) ,#ListParam VARCHAR(100)'
, #Param1
, #Param2
,#Param3
, #ListParam
END
Problem with Other approach
There is a major issue with this other approach, you write your where clause something like...
WHERE ( ColumnName = #Parameter OR #Parameter IS NULL)
The Two major issues with this approach
1) you cannot force SQL Server to check evaluate an expression first like if #Parameter IS NULL, Sql Server might decide to evaluate first the expression ColumnName = #Parameterso you will have where clause being evaluated even if the variable value is null.
2) SQL Server does not do Short-Circuiting (Like C#), even if it decides to check the #Parameter IS NULL expression first and even if it evaluates to true, SQL Server still may go ahead and evaluating other expression in OR clause.
Therefore stick to Dynamic Sql for queries like this. and happy days.
SQL Server does not have a Bool datatype, so you can't assign or return the result of a comparison as a Bool as you would in other languages. A comparison can only be used with IF-statements or WHERE-clauses, or in the WHEN-part of a CASE...WHEN but not anywhere else.
Your specific example would become this:
SELECT * FROM Customers
WHERE 1=1 OR Country IN ('Germany', 'France', 'UK')
It would be better readable to rewrite your statement as follows:
WHERE #PatientID = 0
OR dental.ID_Sick in (1,2)
Referring to your actual question, I'd advise to read the linked question as provided by B House.
May be this straight way will work for you
IF (#PatientID <> 0)
BEGIN
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK')
END
try this:
WHERE 1=(CASE WHEN #PatientID <>0 AND dental.ID_Sick in (1,2) THEN 1
WHEN #PatientID =0 THEN 1
ELSE 0
END)
So this is bit confusing. I already have a stored procedure. I have report which has 5 to 6 parameters. I want it to run the report in such a way that you should be able to select multiple values in the drop down and also keep it optional(not select any values). Other thing is that my parameter value also has NULL values which I have replaced it with NA. I tried using Default Value in the Parameter properties for some selection it works and for some selection it does not. I am still an intermediate person working on SSRS. Any help will be greatly appreciated.
Thanks
I am assuming that you have created a function and used that function in stored procedure to make that stored procedure as multi value selection.
In your function Whichever variable has varchar or any string data type make their size to MAX like varchar(max) and also do the same thing in Stored procedure for parameter.
Reason behind this one: When you provide the data type as varchar(255) it will just take a value for 255 character and if your value character is exceeding that limit then it will truncate the data which is exceeding that limit. And you are making them multi select so probably you need to make them as varchar(max).
Also make the size as Max in stored procedure for parameter.
Note: Varchar(Max) is just an example. You can provide max to any string data type that you have used in function and stored procedure.
Let me know if it works..
ALTER PROCEDURE [dbo].[sp_PIMSelect_AJ_Test]
#network nvarchar(MAX),
--#provider nvarchar(MAX),
--#affiltype varchar(MAX),
--#npi varchar(MAX),
--#tin varchar(MAX),
--#inprovtype varchar (MAX),
#SLG nvarchar(MAX),
#county nvarchar(MAX),
#zip nvarchar(Max),
#specCode nvarchar(Max),
#affiltype nvarchar(Max),
#contract nvarchar(Max)
AS
SET NOCOUNT ON;
select * from (
select
distinct P1.Provid as PIMProviderID,
P.NetworkName,
--COALESCE(pa.affiltype, 'NA') as affiliationtype,
PP1.planprovid as ProviderPlanProvID,
p1.lastname as ProviderLastName,
p1.Firstname as ProviderFirstName,
P1.Profdesig as ProviderTitle,
p1.intprovtype as ProviderIntProvType,
COALESCE(NULLIF(P1.Provtype, ''), 'NA') as ProviderProvType,
XP1.Description as ProviderTypeDescription,
COALESCE(ps1.specialtycode, 'NA') as ProviderSpecialtyCode,
ps1.DirectorySpec as ProviderSpecialityDescription,
ps1.spectype as ProviderSpecType,
p1.CredType as ProviderCredType,
p1.phyaddress1 as ProviderPhyAddress1,
p1.phyaddress2 as ProviderPhyAddress2,
p1.phycity as ProviderPhyCity,
p1.phystate as ProviderPhyState,
p1.phyzipcode as ProviderPhyZipCode,
p1.phycounty as ProviderPhyCounty,
p1.address1 as ProviderMailingAddress1,
p1.address2 as ProviderMailingAddress2,
p1.city as ProviderMailingCity,
p1.state as ProviderMailingState,
p1.Zipcode as ProviderMailingZip,
p1.county as ProviderMailingCounty,
COALESCE(NULLIF(p1.TIN, ''),'0') as ProviderTIN,
COALESCE(NULLIF(p1.NPI, ''),'0') as ProviderNPI,
pa.Affiltype as AffilType,
p.provid as AffilPIMProviderID,
PP.planprovid as AffiliationPlanProvID,
p.Lastname as AffilLastName,
p.Firstname as AffilFirstName,
COALESCE(p.intprovtype, 'NA') as AffilIntProvType,
XP.Description as AffiliationTypeDescription,
ps.specialtycode as AffilSpecialtyCode,
ps.spectype as AffilSpecType,
ps.directoryspec as AffilSpecialtyDescription,
PA.IntDirLocation as AffilDirLocation,
p.phyaddress1 as AffilPhyAddress1,
p.phyaddress2 as AffilPhyAddress2,
p.phycity as AffilPhyCity,
p.phystate as AffilPhyState,
COALESCE(NULLIF(p.phyzipcode, ''), 'NA') as AffilPhyZipCode,
COALESCE(NULLIF(p.phycounty, ''), 'NA') as AffilPhyCounty,
p.address1 as AffilMailingAddress1,
p.address2 as AffilMailingAddress2,
p.city as AffilMailingCity,
p.state as AffilMailingState,
p.Zipcode as AffilMailingZip,
p.county as AffilMailingCounty,
COALESCE(NULLIF(p.TIN, ''),'0') as AffilTIN,
COALESCE(NULLIF(p.NPI, ''),'0') as AffilNPI,
COALESCE(CI.contractid, 'NA') as AffilContractID,
COALESCE(C.description, 'NA') as AffilContractDesc
from ProviderManager.dbo.Provider p
left join ProviderManager.dbo.XProviderTypes XP on P.Provtype = XP.[Provider Type_ID]
left join ProviderManager.dbo.planprovinfo PP on P.Provid = PP.provid
left join ProviderManager.dbo.provspecialty ps on ps.provid = p.Provid
left join ProviderManager.dbo.Affiliation pa on pa.affilid= p.Provid
left join ProviderManager.dbo.provider p1 on p1.provid = pa.provid
left join ProviderManager.dbo.CredApproval CA on P1.NPI = CA.NPI
left join ProviderManager.dbo.planprovinfo PP1 on P1.Provid = PP1.provid
left join ProviderManager.dbo.provspecialty ps1 on p1.Provid = ps1.provid
left join ProviderManager.dbo.XProviderTypes XP1 on P1.Provtype = XP1.[Provider Type_ID]
left join ProviderManager.dbo.contractinfo CI on P1.Provid = CI.provid and P.intprovtype = 'Group' and P.Provid = CI.affilid
left join ProviderManager.dbo.Contract C on CI.contractid
COLLATE SQL_Latin1_General_CP1_CI_AS = C.contractid COLLATE SQL_Latin1_General_CP1_CI_AS) cte
WHERE
cte.ProviderIntProvType IN ('Facility', 'Physician')
and (cte.NetworkName COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#network, ',')))
and (cte.AffilPIMProviderID IN (Select Value from VIB_Extracts.dbo.FnSplit(#SLG, ',')))
and (cte.AffilPhyCounty COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#county, ','))OR (#county = 'NA'))
and (cte.Affilphyzipcode COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#zip, ',')) OR (#zip = 'NA'))
and (cte.ProviderSpecialtyCode COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#specCode, ',')))
and (cte.ProviderProvType COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#affiltype, ',')))
and (cte.AffilContractID COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#contract, ',')))
--and (cte.providerNPI COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#npi,',')))
--and (cte.providerTIN COLLATE DATABASE_DEFAULT IN (Select Value from VIB_Extracts.dbo.FnSplit(#TIN,',')))
Order by Cte.ProviderLastName
USE [VIB_Extracts]
GO
/****** Object: UserDefinedFunction [dbo].[FnSplit] Script Date: 4/29/2017 9:59:16 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[FnSplit]
(
#List nvarchar(MAX),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Value nvarchar(100)
)
AS
BEGIN
While (Charindex(#SplitOn,#List)>0)
Begin
Insert Into #RtnValue (value)
Select
Value = ltrim(rtrim(Substring(#List,1,Charindex(#SplitOn,#List)-1)))
Set #List = Substring(#List,Charindex(#SplitOn,#List)+len(#SplitOn),len(#List))
End
Insert Into #RtnValue (Value)
Select Value = ltrim(rtrim(#List))
Return
END
I'm beginner to T-SQL, I have this issue: I'd like to use a temporary table without creating it, so I wrote this stored procedure :
create PROCEDURE [dbo].[proc_Affaires_By_Client]
#clt_nom varchar(255) ,
#cmd_numero varchar(10),
#etap_cmd_libelle varchar(50),
#typ_cmd_libelle varchar(50)
AS
Begin
DECLARE #temp_tbl_proc TABLE (cmd_code_pk int NOT NULL,
clt_nom varchar(255) NOT NULL,
cmd_nom varchar(100) NOT NULL,
etap_cmd_libelle varchar(50) NULL,
DateAncienTS DateTime NULL,
DateTecentTS DateTime NULL,
TotalHeure numeric(3,2) not null,
TotalHeurePerid numeric(3,2) not null
);
INSERT INTO #temp_tbl_proc(cmd_code_pk, clt_nom, cmd_numero, cmd_nom, etap_cmd_libelle, typ_cmd_libelle, DateAncienTS, DateTecentTS, TotalHeure, TotalHeurePerid)
SELECT
ISNULL(cmd_code_pk, 1) AS cmd_code_pk, clt_nom, cmd_numero,
cmd_nom, etap_cmd_libelle, typ_cmd_libelle,
CONVERT(datetime, '01/01/1900', 103) AS DateAncienTS,
CONVERT(datetime, '01/01/1900', 103) AS DateTecentTS,
-1.00 AS TotalHeure, -1.00 AS TotalHeurePerid
FROM
OPENQUERY(SAB, 'SELECT c.cmd_code_pk, cl.clt_nom, c.cmd_numero, c.cmd_nom,et.etap_cmd_libelle,ty.typ_cmd_libelle FROM commande c,client cl,etape_commande et, type_commande ty where cl.clt_code_pk=c.cmd_clt_fk and c.cmd_etap_cmd_fk = et.etap_cmd_code_pk and c.cmd_typ_cmd_fk = ty.typ_cmd_code_pk' )
SELECT *
FROM #temp_tbl_proc
ORDER BY cmd_nom;
END
The problems are :
the temporary table will be created and added in the database
##query and #query are not recognized as a valid parameter
So how can I fix these problems?
From https://msdn.microsoft.com/en-us/library/ms188427(v=sql.110).aspx
OPENQUERY does not accept variables for its arguments.
So you have to craft a dynamic query, or in your cace, just move the query text into the OPENQUERY
OPENQUERY(SAB, 'Query text comes here')
To pass 'parameters', you can follow the instructions described here: https://support.microsoft.com/en-us/kb/314520
Essentially you have to craft a dynamic query and execute it as a dynamic query text.
You can use the OPENQUERY() a table in queries:
SELECT * FROM OPENQUERY(LinkedServer, 'QueryText') AS R;
Here are some rules to follow:
Add an alias to each returning columns in the QueryText (SQL Server can't handle anonimous columns),
Return only the necessary columns (to decrease the network traffic and the load of the remote and local servers)
You have to add an alias to the OPENQUERY expression in the FROM clause.
So with, a simple example:
DECLARE #localCache TABLE (id INT, col1 VARCHAR(MAX));
INSERT INTO #localCache (id, col1)
SELECT
id, col1
FROM
OPENQUERY(LinkedServer, '
SELECT X.id AS id, Y.col AS col1
FROM X INNER JOIN Y ON X.id = Y.x_id
') src
This could be tricky when you have to pass parameters to the remote query, since you have to create a dynamic query. Dynamic queries are executed in a different context, so the original SP's variables are not available.
DECLARE #myFilter NVARCHAR(32) = 'foo'
DECLARE #dymanicQuery NVARCHAR(MAX) = N'
INSERT INTO #localCache (id, col1)
SELECT
id, col1
FROM
OPENQUERY(LinkedServer, ''
SELECT X.id AS id, Y.col AS col1
FROM X INNER JOIN Y ON X.id = Y.x_id
WHERE Y.col2 = ''''' + #myFilter + '''''
'') src
';
DECLARE #remoteData TABLE (id INT, col1 VARCHAR(MAX));
INSERT INTO #remoteData (id, col1)
EXEC sp_executesql
#stmt = #dymanicQuery
Please note, that this could be dangerous and in this form it is open for sql injecions.
If you can do it, keep the data in sync in a permanent table (using SSIS for example) and use the synchronised data.
I am trying to run a stored procedure in SQL Server and I'm getting 0 results. I initially had this running just fine (attached to SSRS) but then users requested a multiple value input for the ProviderName parameter and I realized I was in over my head. I contacted our vendor who provided a KnowledgeBase article which I essentially copied and pasted right in. See below...
ALTER PROCEDURE [dbo].[Test]
(#dStartDate DATETIME
,#dEndDate DATETIME
,#nProviderName VARCHAR(MAX)
,#nAllProviderName VARCHAR(1) = 'N')
AS
BEGIN
DECLARE #dStart AS DATETIME = CONVERT(DATETIME,CONVERT(DATE,#dStartDate)) ;
DECLARE #dEnd AS DATETIME = DATEADD(ms,-3, DATEADD(day,1,CONVERT(DATETIME,CONVERT(DATE,#dEndDate))))
DECLARE #cProviderName AS VARCHAR(MAX) = #nProviderName
DECLARE #tProviderName AS TABLE (PCPID VARCHAR(MAX) NOT NULL);
IF UPPER(#nAllProviderName) = 'N'
BEGIN
INSERT INTO #tPCPName ( PCPID )
SELECT LTRIM(RTRIM(Item))
FROM [dbo].[Auto_Split]('|',#nProviderName ) ;
END;
SELECT ...
WHERE
([TestMnemonic] = 'GLU' OR
[TestMnemonic] = '%HA1C')
AND [Status] != 'DIS CLI'
AND [TextLine] IS NOT NULL
AND [DateTime] BETWEEN #dStart AND #dEnd
AND (UPPER(#nAllProviderName) = 'Y' OR
[PCPID] COLLATE DATABASE_DEFAULT
IN (SELECT PCPID FROM #tProviderName ) ) ;
END
So if I comment out the last 4 lines of code it runs fine. So it's something in that last bit (or something at the top?) I'm hoping this is a quick fix, any and all help is appreciated!
Thanks!
I'm curious about the Collate statement at the bottom. What us your system default and do you really need that when comparing against a temp table you made?
Without Collate
OR [PCPID] IN (SELECT PCPID FROM #tProviderN
I think you need to switch #tProviderName with #tPCPName in last line.
If your #nAllProviderName is "N" than you search PCPID from memory table called #tPCPName
And there is some code missing, so I didn't get the full picture .. If you could put your from and joins statments and your missing "where clause", when your #nAllProviderName is "Y"
and you don't need this part in your SQL
IF UPPER(#nAllProviderName) = 'N'
BEGIN
INSERT INTO #tPCPName ( PCPID )
SELECT LTRIM(RTRIM(Item))
FROM [dbo].[Auto_Split]('|',#nProviderName ) ;
END
if you switch your last line with
AND (UPPER(#nAllProviderName) = 'Y' OR
[PCPID] COLLATE DATABASE_DEFAULT
IN ( SELECT LTRIM(RTRIM(Item))
FROM [dbo].[Auto_Split]('|',#nProviderName ) ) ) ;
I have a script that pulls a column and some of the cells have nothing so they are returned with a 'dash'. I want these to be replaced with 'Global' but have all the other results retrieved. I don't want to specify each one in a case as they can change from time to time.
Something like this, perhaps?
SELECT CASE
WHEN MyColumn = '-' THEN 'Global'
ELSE MyColumn
END
FROM MyTable
If you can, have a lookup table. Something like
create table ConfigTable
(
pkConfigTable int identity(1, 1) not null primary key clustered,
ConfigKey varchar(100) not null,
ConfigValue varchar(100) not null
)
go
insert into ConfigTable
values('NothingString', '-')
go
declare #NullChar varchar(10)
go
select #NullChar = ConfigValue
from ConfigTable
where ConfigKey = 'NothingString'
go
select
case
when yourColumnToTest = #NullChar
then 'Global'
else yourColumnToTest
end
from yourTable
A simple IF could possibly do:
SELECT
IF(Column = '-', 'Global', Column) AS NiceNameForColumn
FROM
Table
SELECT COALESCE(NULLIF(a_column, '-'), 'Global') AS a_column_narrative
FROM YourTable;