La string dynamic Select a une valeur différente lorsqu'elle est référencée dans la clause Where

Je sélectionne dynamicment une string construite en utilisant une autre string. Donc, si ssortingng1 = 'David Banner', alors MyDynamicSsortingng devrait être 'DBanne'

 Select ... , Left( left((select top 1 strval from dbo.SPLIT(ssortingng1,' ')) //first word ,1) //first character + (select top 1 strval from dbo.SPLIT(ssortingng1,' ') //second word where strval not in (select top 1 strval from dbo.SPLIT(ssortingng1,' '))) ,6) //1st character of 1st word, followed by up to 5 characters of second word [MyDynamicSsortingng] ,... From table1 Join table2 on table1pkey=table2fkey Where MyDynamicSsortingng <> table2.someotherfield 

Je sais que table2.someotherfield n'est pas égal à la string dynamic. Toutefois, lorsque je remplace MyDynamicSsortingng dans la clause Where avec la gauche complète (gauche (etc .. fonction, il fonctionne comme prévu.

Puis-je ne pas referencer cette string plus tard dans la requête? Dois-je le build en utilisant la gauche (gauche (etc ..) fonction chaque fois dans la clause where?

Si vous le faites comme vous l'avez ci-dessus, alors la réponse est oui, vous devez le recréer dans la clause where.

Comme alternative, vous pouvez utiliser une vue en ligne:

  Select ... , X.theSsortingng ,... From table1 Join table2 on table1pkey=table2fkey , (SELECT ssortingng1 ,Left( left((select top 1 strval from dbo.SPLIT(ssortingng1,' ')) //first word ,1) //first character + (select top 1 strval from dbo.SPLIT(ssortingng1,' ') //second word where strval not in (select top 1 strval from dbo.SPLIT(ssortingng1,' '))) ,6) theSsortingng //1st character of 1st word, followed by up to 5 characters of second word FROM table1 ) X Where X.theSsortingng <> table2.someotherfield AND X.ssortingng1 = <whatever you need to join it to> 

Dans SQL 2008, vous pouvez utiliser l'alias dans la clause ORDER BY CLAUSE, mais pas dans la clause where.

Pourquoi ne pas inclure le calcul dans une fonction définie par l'user (UDF) pour éviter de violer DRY et de rendre la requête plus lisible?

Si c'est important, voici un article qui explique pourquoi vous ne pouvez pas utiliser un alias de colonne dans un HAVING, WHERE ou GROUP BY.